So you want to hash a password, store in the DB and go on your merry way. Not being wise in the way of hashing you might think that a simple google for "java MD5 hash" will do you right, but you'd be wrong. In fact it has a good shot of leading you to something like the following (at least 2 examples that I found), which has a cute little bug lurking beneath the surface.

private String hashPassword(String password) {
String hashword = null;
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(password.getBytes());
BigInteger hash = new BigInteger(1, md5.digest());
hashword = hash.toString(16);

} catch (NoSuchAlgorithmException nsae) {

}
return hashword;
}


hashPassword("test")->
98f6bcd4621d373cade4e832627b4f6

but the right answer is:
098f6bcd4621d373cade4e832627b4f6
(note the '0')

The trick of course is that the integer 045 == 45, even in bigInteger land.

A simple

return pad(hashword,32,'0');
private String pad(String s, int length, char pad) {
StringBuffer buffer = new StringBuffer(s);
while (buffer.length() < length) {
buffer.insert(0, pad);
}
return buffer.toString();
}

will sort you.

Glad I chose "test" as a test password or I might have found this at a more unfortunate juncture as the other 3 test users I created worked without a hitch. Amazing to think that in this day and age, blindly copying code from the Internet into you app is still an imperfect method of application development.

Of course if you copy & paste this code, well, that's totally different. It's been tested.. er.. well visually inspected for at least.. um.. a minute.

OMG there's a new Neal Stephenson book.