在公司中一同事用sqlclr写数据迁移自动化执行脚本,发现他在执行脚本时对数据进行了加密。
个人觉得利用sqlclr对数据进行加密是一个解决数据网络安全传输的不错的方案。
以下是一个小的案例:
-------------------------执行:
declare @a nvarchar(100)
declare @b nvarchar(100)
set @a=dbo.fun(‘hi 你好‘)
set @b=dbo.fun1(@a)
print ‘加密后:‘+@a
print ‘解密后:‘+@b
--结果:
加密后:TIIRFZeZjZg=
解密后:hi 你好
-------------------------------------------加密标量函数:
public partial class UserDefinedFunctions
{
[Microsoft.SqlServer.Server.SqlFunction]
public static SqlString Fun(SqlString sql)
{
// 在此处放置代码
return new SqlString(DesEncryptString(sql.Value, "12345678", "12345678"));
}
public static string DesEncryptString(string OriginalString, string EncryptKey, string EncryptOffset)
{
byte[] btKey = Encoding.Default.GetBytes(EncryptKey);
byte[] btIV = Encoding.Default.GetBytes(EncryptOffset);
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
using (MemoryStream ms = new MemoryStream())
{
byte[] inData = Encoding.Default.GetBytes(OriginalString);
try
{
using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(btKey, btIV), CryptoStreamMode.Write))
{
cs.Write(inData, 0, inData.Length);
cs.FlushFinalBlock();
}
return Convert.ToBase64String(ms.ToArray());
}
catch
{
return "";
}
}
}
};
-------------------------------------------解密标量函数:
public partial class UserDefinedFunctions
{
[Microsoft.SqlServer.Server.SqlFunction]
public static SqlString Fun1(SqlString str)
{
// 在此处放置代码
return new SqlString(DesDecryptString(str.Value, "12345678", "12345678"));
}
public static string DesDecryptString(string EncryptedString, string EncryptKey, string EncryptOffset)
{
byte[] btKey = Encoding.Default.GetBytes(EncryptKey);
byte[] btIV = Encoding.Default.GetBytes(EncryptOffset);
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
using (MemoryStream ms = new MemoryStream())
{
byte[] inData = Convert.FromBase64String(EncryptedString);
try
{
using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(btKey, btIV), CryptoStreamMode.Write))
{
cs.Write(inData, 0, inData.Length);
cs.FlushFinalBlock();
}
return Encoding.Default.GetString(ms.ToArray());
}
catch
{
return "";
}
}
}
};