How to hash a text in SQL Server
In this article I am going to show you how to hash a text in SQL Server. First let me explain what is hashing or hash function?
“A hash function is any function that can be used to map digital data of arbitrary size to digital data of fixed size, with slight differences in input data producing very big differences in output data. The values returned by a hash function are called hash values, hash codes, hash sums, or simply hashes”. For more detailed information about hashing algorithms click on the following link Hash Function.
SQL Server has a built-in hashing function and its is called hashbytes(). This function requires 2 parameters in order to work. The first input parameter you need to give is the algorithm. SQL Server has 7 algorithms that can be used in hashing. The algorithms you can use are the followings:
- SHA2_256 (added in SQL Server 2012)
- SHA2_512 (added in SQL Server 2012)
The second parameter is the text or string you want to hash. For better understanding see the code snippet below.
select hashbytes('MD2', 'Barlet') as [Hashing with MD2]
select hashbytes('MD4', 'Barlet') as [Hashing with MD4]
select hashbytes('MD5', 'Barlet') as [Hashing with MD5]
select hashbytes('SHA', 'Barlet') as [Hashing with SHA]
select hashbytes('SHA1', 'Barlet') as [Hashing with SHA1]