JavaScript MD5

For one of my projects, I needed to calculate the MD5 hash function in JavaScript.

I'm a lazy person, and I hate reinventing the wheel. Of course, I googled.

I don't remember why I didn't like the first version found by google. Maybe it was because they hash UCS-2 bytes, while I wanted to hash UTF-8 bytes.

So I used the second one.

Guess what? As frequently happens with public opensource code, it's bugged. BTW, this certainly applies to my source code I've shared on this web site. The implementers incorrectly assumed any byte from UTF-8 can be stored as the character of JavaScript string.

As usually happens with UTF-8 bugs, when the string only contains ASCII characters, everything works great. As soon as the string contain something else (Cyrillic in my case), everything's broken.

I fixed it by replacing string with byte array, and wrote an e-mail to maintainer. However it's 6 months passed already, and the page still lists the bugged version.

So here's my fixed version.

In that project, the hash calculated by JavaScript must match the hash calculated by .NET framework, otherwise the authorised user won't be able to log in. So my MD5 was extensively tested against the .NET implementation.

Developed January, 2010; published July 2010