![](/img/trans.png)
[英]HasDbFunction not mapping the CLR function to the SQL Server function
[英]My SQL Server CLR function is very slow
我在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;
}
通過執行此鏈接中給出的步驟,我已經在SQL Server中創建了CLR函數,並且嘗試將其命名為:
SELECT dbo.Decrypt(MyEncrypted, EncryptionKey)
FROM MyTable
問題是,這花費了太多時間 。 像只有1000行一樣,花了1.5分鍾。 如果我不使用CLR函數調用查詢,則花費了不到1秒的時間。
我可以做些什么來改善CLR功能的性能嗎?
我已經在VS2010中使用性能分析器分析了您的Decrypt
方法,方法是運行100次:
如您所見, Rfc2898DeriveBytes
實例的GetBytes
方法花費的時間最多。
我不確定您為什么具有這些特定的加密/解密要求,但是影響GetBytes
方法花費時間的一種方法是使用將迭代作為第三個參數的構造函數實例化Rfc2898DeriveBytes
。 默認值為1000,我可以將其設置為低至1。 但是強烈建議您這樣做
var pdb = new Rfc2898DeriveBytes(encryptionKey, salt, 10);
對於Encrypt
和Decrypt
,此迭代確實需要相同,因此如果要更改當前值,則必須對Decrypt \\ Encrypt。
另一種選擇可能是按照此答案中的建議緩存IV值。 如果他們還談論使用相同的Key,我還不夠專家,但是如果這是一個選項,那么您也可以將對Key的GetBytes
調用也緩存。
所有描述的更改都會影響數據的加密方式和加密強度。 測試解決方案時,請同時考慮這兩種影響。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.