Crowley Code! 
 (Take 12)

MD5 in XULRunner (or Firefox extensions) 2007/11/15

Rather than including an outside JavaScript library just to do MD5 sums, how about using Mozilla's nsICryptoHash interface?  For the Flickr API, this took slightly more effort than expected because it only returns data in base64-encoded ASCII or binary.  Fortunately for me, the binary format was packed as a string, so making this usable was a matter of a little bin2hex function.  Behold:

var _md5 = null;
try {
	_md5 = Cc['@mozilla.org/security/hash;1'].createInstance(Ci.nsICryptoHash);
} catch (err) {
	Components.utils.reportError(err);
}
var md5 = function(str) {
	if (null == _md5) {
		return '';
	}

	// Build array of character codes to MD5
	var arr = [];
	var ii = str.length;
	for (var i = 0; i < ii; ++i) {
		arr.push(str.charCodeAt(i));
	}
	_md5.init(Ci.nsICryptoHash.MD5);
	_md5.update(arr, arr.length);
	var hash = _md5.finish(false);

	// Unpack the binary data bin2hex style
	var ascii = [];
	ii = hash.length;
	for (var i = 0; i < ii; ++i) {
		var c = hash.charCodeAt(i);
		var ones = c % 16;
		var tens = c >> 4;
		ascii.push(String.fromCharCode(tens + (tens > 9 ? 87 : 48)) +
			String.fromCharCode(ones + (ones > 9 ? 87 : 48)));
	}

	return ascii.join('');
};

Comments (4)

  1. Should really do === when comparing to null :p

    Running away b/c I don't even get what the hell is going on in this function...

    Dimitry — 2007/11/15 10:18 pm

  2. Great stuff, I was just trying to use JS MD5 on bigger files (~1MB) in my extension. It timed out a couple of times before finished calculating. This is fast and should be used instead!

    — Kojalaharcos — 2008/01/02 3:38 pm

  3. i found many sites that give md5 coding and decoding like http://www.joomlaaa.com/md5-coding-decoding i do not know how they can decode md5 anyone know a script to decode md5

    — michosn — 2008/04/30 3:51 am

  4. michosn: Please kill yourself.

    — Mike D — 2008/04/30 8:12 am

Richard Crowley?  Kentuckian engineer who cooks and eats in between bicycling and beering.

I blog mostly about programming and databases.  Browse by month or tag.

To blame for...


© 2009 Richard Crowley.  Managed by Bashpress.