Javascript Equivalent of C# MD5

Started by
2 comments, last by Adam_42 12 years, 2 months ago
Actually, it's Javascript, but that's a different matter entirely. I have the following C# code that simply takes a string and encodes it:


public string CalculateMD5Unicode(string input)
{
// step 1, calculate MD5 hash from input
MD5 md5 = System.Security.Cryptography.MD5.Create();
byte[] inputBytes = System.Text.Encoding.Unicode.GetBytes(input);

byte[] hash = md5.ComputeHash(inputBytes);

return Convert.ToBase64String(hash);
}


Now I need to duplicate the output of this code in Javascript. So far, I've gotten it to where the same bytes are extracted:


function Process(str)
{

var ch;
var bytes = [];
for(var i = 0; i < str.length; i++)
{
ch = str.charCodeAt(i);
bytes.push(ch & 0xFF, ch>>>8);
}
}


But I've hit a bit of a snag in trying to get the MD5 values to match. Specifically, this will be called from an HTML form to generate the same data currently being generated in the compiled C# program.

And yes, I know MD5 hashing is not terribly secure for doing passwords and what-not, but this is only going to be used until this gets closer to being released. Taking a lot of work to convince the guys in charge to buy an SSL certificate as they don't see it as being needed for testing. Isn't it fun to work for people who just don't know how to do...well anything tongue.png
My name is "Todd". Drop the "T" and it explains sooooooo much! :P
Advertisement
The power of Google compels you (really, there's tons of those).


MD5 hashes may be salted, so while algorithm remains the same, result is different. See .Net documentation on how exactly their cryptography works. If it's just about hash, there shouldn't any problems. If hash is used only to initialize some other seed or encryption, then one would need to replicate same process in JS.

I'd advise against implementing MD5 in JS on your own, the code is just messy since JS lacks some useful operations.
I had noticed that. Part of why I was hoping for something simpler like just getting the SSL now instead of waiting. The code will just have to be changed to use it then, so why not do it right the first time?

Unfortunately it's a matter of determining how C# gets its results and finding the matching Javascript version that's out there. Something tells me this is not a common problem :P
My name is "Todd". Drop the "T" and it explains sooooooo much! :P
You can always make your own self signed SSL certificate for free. The browser will complain loudly about it, but you can use it for testing purposes.

This topic is closed to new replies.

Advertisement