Thursday, February 26, 2009

MD5 hash, Java vs Ruby

I needed to create a small program that would create a MD5 hexadecimal hash for a password. First I implemented this using Java.

import java.security.MessageDigest;
public class TestMD5 {
public static void main (String [] args) {
try {
String passwd = "password";
MessageDigest md =
MessageDigest.getInstance("MD5");
byte[] hash = md.digest(passwd.getBytes());
StringBuffer hexstr = new StringBuffer();
for (int i = 0; i < hash.length; i++) {
String hex = Integer.toHexString(
hash[i] & 0xFF);
if (hex.length() == 1) {
hexstr.append('0');
}
hexstr.append(hex);
}
System.out.println(hexstr.toString());
} catch (Exception ex) {
ex.printStackTrace();
}
}
}


Note: java.lang.Integer.toHexString does not add leading zeros. Without the length check after this function the hash string will not always be 32 charaters long.


Since I have started working with Ruby on Rails, I was curious to see how I would implement this in Ruby.

#!/usr/bin/ruby
require 'digest/md5'
passwd = "password"
digest = Digest::MD5.hexdigest(passwd)
puts digest


In this case Ruby wins for having to write less code to get the same result.

No comments:

Post a Comment