Search

Thursday, July 19, 2012

HashBytes Function to implement a one way hash

In below script I have chosen to use SHA1 for this demo which produces an 160-bit (20 byte) hash.

SELECT CAST(REPLICATE('Z',1024) AS NVARCHAR(1024))  
-- returns me a string of 1024 'Z' characters  
  
SELECT LEN(CAST(REPLICATE('Z',1024) AS NVARCHAR(1024)))  
-- clarifies the length is 1024   
  
SELECT DATALENGTH(CAST(REPLICATE('Z',1024) AS NVARCHAR(1024)))  
-- shows the real storage length is 2048 (unicode, i.e. Nvarchar requires double byte storage)  
  
SELECT HASHBYTES('SHA1', CAST(REPLICATE('Z',1024) AS NVARCHAR(1024)))  
-- shows the MD5 hash of that Nvarchar string  
  
SELECT LEN(HASHBYTES('SHA1', CAST(REPLICATE('Z',1024) AS NVARCHAR(1024))))  
-- confirms the length of that MD5 hash is 20  
  
DECLARE @myhash VARBINARY(20)  
SELECT @myhash = HASHBYTES('SHA1', CAST(REPLICATE('Z',1024) AS NVARCHAR(1024)))  
-- assigns varbinary hash to variable  




No comments:

Post a Comment