using System; public class HashProc { [Microsoft.SqlServer.Server.SqlFunction(IsDeterministic = true, DataAccess = Microsoft.SqlServer.Server.DataAccessKind.None)] public static void SHA256(string inputStr, out string outputStr) { using (System.Security.Cryptography.SHA256Managed SHA256Crypto = new System.Security.Cryptography.SHA256Managed()) { byte[] input = System.Text.Encoding.UTF8.GetBytes(inputStr); input = SHA256Crypto.ComputeHash(input); System.Text.StringBuilder output = new System.Text.StringBuilder(); foreach (byte b in input) { output.Append(b.ToString("x2", System.Globalization.CultureInfo.InvariantCulture).ToUpperInvariant()); } outputStr = output.ToString(); } } }
2. Enable CLR in SQL server
sp_configure 'show advanced options', 1; GO RECONFIGURE; GO sp_configure 'clr enabled', 1; GO RECONFIGURE; GO
3. Register HashProc.dll into SQL server as a assembly
CREATE ASSEMBLY hashproc from 'C:\path\to\HashProc.dll' WITH PERMISSION_SET = SAFE; GO
4. Create stored procedure to call the assembly hashproc
CREATE PROCEDURE sp_hash @inputStr nvarchar(250), @outputStr nvarchar(250) OUT AS EXTERNAL NAME hashproc.HashProc.SHA256; GO
5. Call the stored procedure
DECLARE @outputStr nvarchar(250) EXEC [dbo].[sp_hash] @inputStr = N'Test', @outputStr = @outputStr OUTPUT SELECT @outputStr as N'@outputStr' GO
Note: Confirm your SQL server CLR version supported using
select * from sys.dm_clr_properties;
That's all. You can change the HashProc class to using some more cryptography as SHA384 or SHA512 etc.
2 comments:
One thing you neglected to mention is that the DLL needs to be signed with a strong name.
Other than that, excellent article. Worked perfectly once I signed the compiled DLL.
Thanks!
Hello! Amazing work you have. I have a project I would really like to work with you. Please contact me to neilxr@gmail.com
Post a Comment