MD5 Hashed code differs by datatype in SQLServer HASHBYTES ( algm, str) function


Issue:
 HASHBYTES ( algm, str) function generated hash code differ from regular/ other MD5 programs by the data type. 

Data: 'mypassword1'
 If you pass a variable as below as mentioned in the link in 'Ref' below,

 DECLARE @HashThis nvarchar(4000);
SELECT @HashThis = CONVERT(nvarchar(4000),'mypassword1');
SELECT HASHBYTES('MD5', @HashThis );
GO


---- This will generate a Hashed code : 
0xBAE02911AA20CACE81224DCA98610B05

If you try the same in different MD5 generator tool like this website :  Type 'mypassword1'
http://www.miraclesalad.com/webtools/md5.php

---- the generated Hashed code will be, 
0d28e4080dc8f64fc9603639bb7aa1b9

Hashcodea are different.


Cause:
SQL Server differs the algorithm by the data type - here it is not just string , it is nvarchar / varchar - SQL Server adds up spaces or truncate them as to the size of the data.

DECLARE @HashThis nvarchar(4000);
SELECT @HashThis = CONVERT(nvarchar(4000),'mypassword1');
SELECT HASHBYTES('MD5', @HashThis );


But in MYSQL Database you can use 
select md5('mypassword1') ;  and get the right Hashcode generated.

Fix:
1. Use the right size and  data type. or

2. Use the string directly in the function parameter.
SELECT HASHBYTES('MD5', 'mypassword1' );
Go

---- the generated Hashed code will be,
0x0D28E4080DC8F64FC9603639BB7AA1B9

Ref:
To Hash a data / password in SQL Server you could use 


HASHBYTES ( '<algorithm>', { @input | 'input' } ) 

<algorithm>::= MD2 | MD4 | MD5 | SHA | SHA1 | SHA2_256 | SHA2_512 
Microsoft Link:
http://technet.microsoft.com/en-us/library/ms174415.aspx

http://www.miraclesalad.com/webtools/md5.php

Comments