Introduction

SHA (Secure Hash Algorithm) is a family of cryptographic hash functions that produce a fixed-size hash value from input data. SQL Server provides functions for working with cryptographic hashes, including SHA algorithms. Here's how you can use the SHA algorithms in SQL Server.

SHA-1

SQL Server provides the HASHBYTES function that allows you to compute a SHA-1 hash value for a given input string. Here's an example.

DECLARE @InputString NVARCHAR(100) = 'Hello, world!';

DECLARE @HashValue VARBINARY(20);

SET @HashValue = HASHBYTES('SHA1', @InputString);

SELECT @HashValue AS SHA1Hash;

SHA-256

SQL Server also supports the SHA-256 hash algorithm using the HASHBYTES function. SHA-256 produces a 256-bit hash value.

DECLARE @InputString NVARCHAR(100) = 'Hello, world!';

DECLARE @HashValue VARBINARY(32);

SET @HashValue = HASHBYTES('SHA2_256', @InputString);

SELECT @HashValue AS SHA256Hash;

SHA-512

Similarly, SQL Server supports the SHA-512 hash algorithm, which produces a 512-bit hash value.

DECLARE @InputString NVARCHAR(100) = 'Hello, world!';

DECLARE @HashValue VARBINARY(64);

SET @HashValue = HASHBYTES('SHA2_512', @InputString);

SELECT @HashValue AS SHA512Hash;

Please note that the HASHBYTES function returns the hash value as a VARBINARY type. If you want to display the hash value as a string, you can use the CONVERT function to convert it to a hexadecimal representation.

SELECT CONVERT(NVARCHAR(MAX), @HashValue, 2) AS HexadecimalHash;

Keep in mind that SHA-1 is considered weak and insecure for many cryptographic purposes due to vulnerabilities discovered over time. SHA-256 and SHA-512 are currently more secure options.

When to use SHA hashes?

How to use SHA in SQL Server?

HASHBYTES('SHA2_512', 'SomeStringData')

Benefits of Using SHA Hashing

Summary

SQL Server's SHA hash functions are most useful for securely storing sensitive data, validating data integrity, and generating unique fingerprint values of data.