How do you use the HASHBYTES function to compute a hash value for a given input?
Posted by FrankMl
Last Updated: July 27, 2024
In SQL Server, the HASHBYTES function is used to compute a hash value from a given input string. This function supports several hashing algorithms, including MD2, MD4, MD5, SHA, SHA1, SHA2_256, and SHA2_512. Here's how to use the HASHBYTES function:
Syntax
HASHBYTES ( 'algorithm_name', 'input_string' )
- algorithm_name: A string that specifies the algorithm to use. This can be one of the following: - MD2 - MD4 - MD5 - SHA - SHA1 - SHA2_256 - SHA2_512 - input_string: The string input for which the hash value will be computed. This can be a binary or character expression.
Example Usage
Here’s an example of how to use HASHBYTES to compute a hash value:
-- Using MD5 algorithm
SELECT HASHBYTES('MD5', 'Hello, World!') AS HashValue;

-- Using SHA2_256 algorithm
SELECT HASHBYTES('SHA2_256', 'Hello, World!') AS HashValue;

-- Using SHA2_512 algorithm
SELECT HASHBYTES('SHA2_512', 'Hello, World!') AS HashValue;
Notes
- The output of HASHBYTES is of type varbinary, which means you'll see it as a series of bytes. - Make sure that the algorithm you choose is appropriate for your use case. For example, MD5 is generally not recommended for security-sensitive applications due to its vulnerabilities.
Example Output
If you run the above queries in SQL Server, you’ll get output resembling the following (note that actual values may vary):
HashValue
------------------------------------
0x65A5051AE88BCA704AE254A517B8A8BC  -- MD5
0xA591A6D40BF420404A011733CFB7B190  -- SHA2_256
0x45C48C3B907D3A6E44B9B3A154D4A466  -- SHA2_512
In summary, to compute a hash value using the HASHBYTES function, specify the desired algorithm and the input string, and then run the query to get the resulting hash.
Related Content
C++ Hash Function
C++ Hash Function
Samath | Jan 05, 2017