Calculate MD5 , SHA256, SHA512 in SQL Server

access_time 4 months ago visibility102 comment 0

SQL Server has built-in function HASHBYTES that can be used to calculate hash values. The supported hash algorithms include MD2, MD4, MD5, SHA, SHA1, SHA2_256 and SHA2_512.

Function HASHBYTES 

The signature of this function is:

HASHBYTES ( '<algorithm>', { @input | 'input' } )  
  
<algorithm>::= MD2 | MD4 | MD5 | SHA | SHA1 | SHA2_256 | SHA2_512 

Examples

MD5

SELECT HASHBYTES('MD5','abc');

Output:

0x900150983CD24FB0D6963F7D28E17F72

SHA256

SELECT HASHBYTES('SHA2_256','abc');

Output:

0xBA7816BF8F01CFEA414140DE5DAE2223B00361A396177A9CB410FF61F20015AD

SHA512

SELECT HASHBYTES('SHA2_512','abc');

Output:

0xDDAF35A193617ABACC417349AE20413112E6FA4E89A97EA20A9EEEE64B55D39A2192992A274FC1A836BA3C23A3FEEBBD454D4423643CE80E2A9AC94FA54CA49F

Return hexadecimal string

Function HashBytes returns VARBINARY; use CONVERT function to convert the binary to string:

SELECT CONVERT(VARCHAR(100),HASHBYTES('MD5','abc'),1);
SELECT CONVERT(VARCHAR(100),HASHBYTES('MD5','abc'),2);

Results:

0x900150983CD24FB0D6963F7D28E17F72
900150983CD24FB0D6963F7D28E17F72

References

HASHBYTES (Transact-SQL)

copyright This page is subject to Site terms.
Like this article?
Share on

Please log in or register to comment.

account_circle Log in person_add Register

Log in with external accounts

Follow Kontext

Get our latest updates on LinkedIn or Twitter.

Want to publish your article on Kontext?

Learn more

More from Kontext

visibility 970
thumb_up 0
access_time 11 years ago

我们都知道在一个表中当需要2列以上才能确定记录的唯一性的时候,就需要用到联合主键,当建立联合主键以后,在查询数据的时候性能就会有很大的提升,不过并不是对联合主键的任何列单独查询的时候性能都会提升,但我们依然可以通过对联合主键中的首列除外的其他列建立非聚集索引来提高性能。关于索引,可以参考我的这篇文章:http://hi.baidu.com/1987raymond/blog/item/a0f7b11062e1330a213f2e26.html

visibility 35
thumb_up 0
access_time 2 years ago

This code snippet shows how to calculate time differences.

visibility 15
thumb_up 0
access_time 30 days ago

In article Connect to SQL Server in Spark (PySpark) ,  I showed how to connect to SQL Server in PySpark. Data can be loaded via JDBC, ODBC and Python drivers. In this article, I will directly use JDBC driver to load data from SQL Server with Scala. Download Microsoft JDBC Driver for SQL ...