MSSQL 调用 CLR 加密/解密
2022/7/29 2:53:35
本文主要是介绍MSSQL 调用 CLR 加密/解密,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
使用 Transact-SQL开启CLR
sp_configure 'show advanced options',1 RECONFIGURE sp_configure 'clr enabled',1 RECONFIGURE
DECLARE @hash AS BINARY(64) = (SELECT HASHBYTES('SHA2_512', (SELECT * FROM OPENROWSET (BULK 'C:\clrDES.dll', SINGLE_BLOB) AS [Data]))) EXEC sp_add_trusted_assembly @hash
编写CLR集成托管DLL
using System; using System.IO; using System.Text; using System.Data; using System.Data.SqlTypes; using System.Security.Cryptography; using Microsoft.SqlServer.Server; public class DES { [SqlFunction(IsDeterministic = true, IsPrecise = true)] public static SqlString DESEncrypt(SqlString text, SqlString key) { if (text.IsNull || key.IsNull || key.Value.Length < 8) return null; return (SqlString)_DESEncrypt(Encoding.Default.GetBytes((string)text), Encoding.Default.GetBytes((string)key), new byte[] { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF }); } private static string _DESEncrypt(byte[] text, byte[] key, byte[] iv) { string entext; using (MemoryStream mstream = new MemoryStream()) { DESCryptoServiceProvider des = new DESCryptoServiceProvider(); CryptoStream estream = new CryptoStream(mstream, des.CreateEncryptor(key, iv), CryptoStreamMode.Write); try { estream.Write(text, 0, text.Length); estream.FlushFinalBlock(); entext = Convert.ToBase64String(mstream.ToArray()); } finally { estream.Close(); des.Clear(); } } return entext; } [SqlFunction(IsDeterministic = true, IsPrecise = true)] public static SqlString DESDecrypt(SqlString text, SqlString key) { if (text.IsNull || key.IsNull || key.Value.Length < 8) return null; return (SqlString)_DESDecrypt(Convert.FromBase64String((string)text), Encoding.Default.GetBytes((string)key), new byte[] { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF }); } private static string _DESDecrypt(byte[] text, byte[] key, byte[] iv) { string detext; using (MemoryStream mstream = new MemoryStream()) { DESCryptoServiceProvider des = new DESCryptoServiceProvider(); CryptoStream estream = new CryptoStream(mstream, des.CreateDecryptor(key, iv), CryptoStreamMode.Write); try { estream.Write(text, 0, text.Length); estream.FlushFinalBlock(); detext = Encoding.Default.GetString(mstream.ToArray()); } finally { estream.Close(); des.Clear(); } } return detext; } }
调用示例
select dbo.des_encrypt(N'hello world', N'88888888'); select dbo.des_decrypt(N'+GeLDT6kAxZlm2pnFX8X4w==',N'88888888');
这篇关于MSSQL 调用 CLR 加密/解密的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-01-08Docker下的SqlServer发布订阅启用
- 2023-06-05Docker安装MS SQL Server并使用Navicat远程连接
- 2023-05-25深入浅出 SQL Server CDC 数据同步
- 2023-05-12通过空间占用和执行计划了解SQL Server的行存储索引
- 2023-04-24以SQLserver为例的Dapper详细讲解
- 2022-11-30SQL server高级函数查询
- 2022-11-26SQL SERVER数据库服务器CPU不能全部利用原因分析
- 2022-11-21SQL Server 时间算差值/常用函数
- 2022-11-20调试Archery连接SQL Server提示驱动错误
- 2022-10-22SQL Server 完整、差异备份+完整、差异还原(详细讲解,规避错误)