Get short hash value from the HASHBYTES('SHA1', text) independent on the SQL Server version?

1k views Asked by At

For the purpose of getting the content-derived key of a longer text, I do calculate HASHBYTES('SHA1', text). It returns 20 bytes long varbinary. As I know the length of the result, I am storing it as binary(20).

To make it shorter (to be used as a key), I would like to follow the Git idea of a short hash -- as if the first (or last) characters of the hexadecimal representation. Instead of characters, I would like to get binary(5) value from the binary(20).

When trying with the SQL Server 2016 it seems that the following simple way:

DECLARE @hash binary(20) = HASHBYTES('SHA1', N'příšerně žluťoučký kůň úpěl ďábelské ódy')
DECLARE @short binary(5) = @hash

SELECT @hash, @short

Returns the leading bytes (higher order bytes):

(No column name)                            (No column name)
0xE02C3C55FBA0DF13ADA1B626B1E31746D57B4602  0xE02C3C55FB

However, the documentation (https://learn.microsoft.com/en-us/sql/t-sql/data-types/binary-and-varbinary-transact-sql?view=sql-server-ver15) warns that:

Conversions between any data type and the binary data types are not guaranteed to be the same between versions of SQL Server.

Well, this is not exactly a conversion. Still, does this uncertainty hold also for getting shorter version of binary from the longer version of binary? What should I expect for future versions of SQL Server?

0

There are 0 answers