Sampath Sampath - 1 year ago 110
Javascript Question

MD5 hash is Different

On sql server : Out put :


SELECT HASHBYTES('MD5', convert(varchar,getdate(),112)+'mytest@+')

On JavaScript : Out put :

//to get Md5 Hash bytes
vm.getMd5Hashbytes = function () {
var currentDate = moment().format('YYYYMMDD');
var md5Hash = md5.createHash(currentDate + 'mytest@+');
return md5Hash;

angular-md5 module

Q : Can you tell me why this difference ? SQL server shows
as prefix.Why ?

Answer Source

I am not sure how else to explain it but it will take more space than a comment allows for so I will post it as an answer.

Look at the source code that you are referencing. At the end (lines 210 and 212) you will see it converts the binary value to a hex string (and then to lower case which does not matter unless you opt for a string comparison at the end). End result = your JavaScript library returns a representation using the type string formatted as hex.

Your Sql function HASHBYTES on the other hand produces a varbinary typed result (which is a different type than string (varchar)).

So you have 2 different data types (each living on their own space as you have not pulled one to the other). You never mention where you are doing the comparison, ie: on the database or are you pulling from the database to script. Either way to do a comparison you need to convert one type so you are either comparing 2 strings types OR comparing two binary types. If you do not compare similar types you will get unexpected results or run time exceptions.

If you are comparing using strings AND in JavaScript then look at your library that you are referencing, it already has a call named wordToHex, copy and paste it and reuse it to convert your Sql result to a string and then do a string comparison (do not forget to compare case insensitive or also make it lower case).


WebApi is black box for me.It is a 3rd party service.I just need to send the security token as mentioned above.

Assuming that the type accepted by that web api is byt[] appending 0x to your string in javascript and then sending it to the web api should work as in the web api will then translate the incoming parameter as a byte array and execute the comparison using the correct types. As this is a black box there is no way to know for certain unless you either ask them if the accepted type is indeed a byte array or to test it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download