我编写了以下代码来解密一些敏感数据,在大多数情况下我需要使用T-SQL查询数据,我无法解密由此代码加密的数据。所以我的问题是如何在T-SQL中编写一个函数,其工作方式与在C#中工作的方式相同,我将在存储过程中使用它。
先谢谢
加密功能:
public static string Encrypt(string text)
{
if (string.IsNullOrEmpty(EncryptionKey))
return string.Empty;
if (string.IsNullOrEmpty(text))
return string.Empty;
var clearBytes = Encoding.Unicode.GetBytes(text);
using (var encryptor = Aes.Create())
{
var pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[]
{
0x49,
0x76,
0x61,
0x6e,
0x20,
0x4d,
0x65,
0x64,
0x76,
0x65,
0x64,
0x65,
0x76
});
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (var ms = new MemoryStream())
{
using (var cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(clearBytes, 0, clearBytes.Length);
}
text = Convert.ToBase64String(ms.ToArray());
}
}
return text;
}
解密功能:
public static string Decrypt(string text)
{
if (string.IsNullOrEmpty(EncryptionKey))
return string.Empty;
if (string.IsNullOrEmpty(text))
return string.Empty;
var cipherBytes = Convert.FromBase64String(text);
using (var encryptor = Aes.Create())
{
var pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[]
{
0x49,
0x76,
0x61,
0x6e,
0x20,
0x4d,
0x65,
0x64,
0x76,
0x65,
0x64,
0x65,
0x76
});
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (var ms = new MemoryStream())
{
using (var cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(cipherBytes, 0, cipherBytes.Length);
}
text = Encoding.Unicode.GetString(ms.ToArray());
}
}
return text;
}
答案 0 :(得分:3)