在关注AesCryptoServiceProvider
AesCryptoServiceProvider.CreateEncryptor
示例(https://msdn.microsoft.com/en-us/library/bb356459(v=vs.110).aspx)后,查看此MSDN文章后,请参阅下面的代码片段。安全地对AES加密字符串进行不区分大小写的查找?
static string EncryptStringToBytes_Aes(string plainText, byte[] Key, byte[] IV)
{
// Check arguments.
if (plainText == null || plainText.Length <= 0)
throw new ArgumentNullException("plainText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("IV");
byte[] encrypted;
// Create an AesCryptoServiceProvider object
// with the specified key and IV.
using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
{
aesAlg.Key = Key;
aesAlg.IV = IV;
// Create a decrytor to perform the stream transform.
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
// Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(plainText);
}
encrypted = msEncrypt.ToArray();
}
}
}
return Convert.ToBase64String(encrypted);
}
我可以用这个方法成功生成的加密字符串,但是当我开始保存加密的字符串在SQL数据库中,我意识到,任何查找将不区分大小写。我的问题是,使用这种方法对加密值进行不区分大小写查找可以吗?该方法将产生相同的字符串,但在不同的情况下有什么机会呢?
另一种选择是从数据库中检索值并在内存中执行区分大小写的查找,但我试图避免这种情况。
技术使用。 C#,EntityFramework,Azure SQL Server 2016,ASP.NET MVC,WEB API
当前值是byte [],对此问题没有意义。如果它变成了一个字符串,那么你(有效)有两个选择:Base64和十六进制。对于十六进制的情况是无关紧要的。对于Base64而言,它很重要,因此不能无匹配地匹配。 – bartonjs
啊,当然,我忘了添加我的其他代码,做'返回Convert.ToBase64String(加密);'。转换为十六进制是有道理的。我很想知道其他人如何处理SQL大小写敏感问题。 – gorillapower
通过将其保存为十六进制或base32而不是base64 :) – bartonjs