【发布时间】:2015-11-09 03:22:18
【问题描述】:
我在 C# 中创建了两个方法:
public static string Encrypt(string clearText, string encryptionKey)
{
byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
using (Aes 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);
cs.Close();
}
clearText = Convert.ToBase64String(ms.ToArray());
}
}
return clearText;
}
public static string Decrypt(string cipherText, string encryptionKey)
{
try
{
byte[] cipherBytes = Convert.FromBase64String(cipherText);
using (Aes 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);
cs.Close();
}
cipherText = Encoding.Unicode.GetString(ms.ToArray());
}
}
}
catch (Exception)
{
}
return cipherText;
}
按照This Link 中给出的步骤,我在 SQL Server 中创建了一个 CLR 函数,我尝试将其称为:
SELECT dbo.Decrypt(MyEncrypted, EncryptionKey)
FROM MyTable
问题是,它花费了 太多时间。就像只有 1000 行一样,需要 1.5 分钟。如果我在没有 CLR 函数的情况下调用我的查询,则只需不到 1 秒。
我可以做些什么来提高 CLR 函数的性能?
【问题讨论】:
-
可以使用sql server的加密吗?当你可以保存原始字节时,为什么要将它保存为字符串?
-
会提高性能吗?
-
也许吧。你必须测试它。
-
“MyEncrypted”和“EncryptionKey”列的数据大小是多少?在具有完全相同输入的 C# 控制台应用程序中运行该代码需要多长时间?
-
@jdweng OP 将此代码用作 CLR 函数,因此它在 sqlserver 上运行,在同一进程中但在单独的应用程序域中,不涉及防火墙...
标签: c# .net sql-server performance clr