为什么不在代码中而不是在查询中实现加密/解密?
private static Byte[] Encrypt(String toEncrypt, Byte[] Key, Byte[] IV)
{
CryptoStream streamCrypto = null;
MemoryStream streamMemory = null;
RijndaelManaged aes = null;
StreamWriter streamWriter = null;
try
{
aes = new RijndaelManaged();
aes.Key = Key;
aes.IV = IV;
ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
streamMemory = new MemoryStream();
streamCrypto = new CryptoStream(streamMemory, encryptor, CryptoStreamMode.Write);
streamWriter = new StreamWriter(streamCrypto);
streamWriter.Write(toEncrypt);
}
finally
{
if (streamWriter != null)
streamWriter.Close();
if (streamCrypto != null)
streamCrypto.Close();
if (streamMemory != null)
streamMemory.Close();
if (aes != null)
aes.Clear();
}
return streamMemory.ToArray();
}
public static String Decrypt(Byte[] toDecrypt, Byte[] Key, Byte[] IV)
{
CryptoStream streamCrypto = null;
MemoryStream streamMemory = null;
RijndaelManaged aes = null;
StreamReader streamReader = null;
String output = null;
try
{
aes = new RijndaelManaged();
aes.Key = Key;
aes.IV = IV;
ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
streamMemory = new MemoryStream(toDecrypt);
streamCrypto = new CryptoStream(streamMemory, decryptor, CryptoStreamMode.Read);
streamReader = new StreamReader(streamCrypto);
output = streamReader.ReadToEnd();
}
finally
{
if (streamReader != null)
streamReader.Close();
if (streamCrypto != null)
streamCrypto.Close();
if (streamMemory != null)
streamMemory.Close();
if (aes != null)
aes.Clear();
}
return output;
}
在您的代码中,您加密您的字符串,然后将加密数据发送到数据库:
Byte[] encrypted = Encrypt(yourString, Key, IV);
当您从数据库中提取数据时,您只需使用以下命令取回字符串:
String decrypted = Decrypt(dbData, Key, IV);
如果您不喜欢这种方式,只需像这样使用您的查询:
INSERT INTO mysecrets (mysecret1, mysecret2) VALUES (AES_ENCRYPT(secret1, YOUR_ENCRYPTION_KEY), AES_ENCRYPT(secret2, YOUR_ENCRYPTION_KEY))
SELECT AES_DECRYPT(mysecret1, YOUR_ENCRYPTION_KEY) AS secret1, AES_DECRYPT(mysecret1, YOUR_ENCRYPTION_KEY) AS secret2 FROM mysecrets