Encrypt With MD5, SHA Or SHA1 In MS SQL Server
Posted by in SQL Server April 18, 2012 Leave a comment

This article shows SQL statements that encrypt an input string by using MD5/SHA/SHA1 algorithm. And you should play with these SQL statements in the Microsoft SQL Server Management Studio (New Query) to see the results.

MD5/SHA/SHA1 Hash

SQL statements below returns the MD5, SHA, SHA1 hash of ’123456′ string.

SELECT HashBytes('MD5','123456') 
SELECT HashBytes('SHA','123456')
SELECT HashBytes('SHA1','123456')
SQL statements Encrypt MD5 SHA SHA1

SQL statements Encrypt MD5 SHA SHA1

However, those return VarBinary instead of VarChar values:

0xE10ADC3949BA59ABBE56E057F20F883E
0x7C4A8D09CA3762AF61E59520943DC26494F8941B

Therefore, we need to use the built in function, fn_varbintohexstr from VarBinary to Hex String:

SELECT SUBSTRING(master.dbo.fn_varbintohexstr(HashBytes('MD5', '123456')), 3, 32) AS MD5
SELECT SUBSTRING(master.dbo.fn_varbintohexstr(HashBytes('SHA', '123456')), 3, 40) AS SHA
SELECT SUBSTRING(master.dbo.fn_varbintohexstr(HashBytes('SHA1', '123456')), 3, 40) AS SHA1
SQL Statement Encrypt MD5 SHA SHA1 From VarBinary To Hex String

SQL Statement Encrypt MD5 SHA SHA1 From VarBinary To Hex String

Note: in order to verify the MD5 result, you can use the Online Tool MD5 Generator.

Hoan Huynh is the founder and head of 4rapiddev.com. Reach him at hoan@4rapiddev.com