Skip to content
Advertisement

How to reproduce the behavior of SQL NVARCHAR in Python when generating a SHA-512 hash?

I have the following SQL query

SELECT CONVERT(VARCHAR(254), HASHBYTES('SHA2_512', CONVERT(NVARCHAR(24), '2020-05-27 00:00:00.000', 127)), 2)

that generates the hash value

E8FD9193FA939608DF127AC73428EB39F66CB6F44440083EF269A1F72176BF7BF80C3EB26BA43277E6F9CFFB4F7AFC6AA83AF527BEDF887E4EE06BA492CAD3BE

out of todays date and I want to reproduce this hash in Python with

hashlib.sha512('2020-05-27 00:00:00.000'.encode()).hexdigest().upper()

but I get

FE48F900755B4C19039E6886148566DF93730A7887771C7A72260BB4E784080CDDA6C70C428A6EEFED658846F45F3D153C6B6472C04508B9242C14C61BD1C1BE

as hash value. When I use VARCHAR instead of NVARCHAR I get the correct hash value. How can I reproduce the bahavior of NVARCHAR in Python?

Advertisement

Answer

NVARCHAR encodes to UTF-16LE. Adding it to

hashlib.sha512('2020-05-27 00:00:00.000'.encode('utf_16_le')).hexdigest().upper()

creates the correct hash value.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement