Jun 07

Why doesn’t the standard Java SDK provide a method that returns a 32 character (128bit) String representation of  an MD5 encrypted string… just like most other languages do (PHP, Ruby)… i don’t know! Below are Ruby and PHP examples and then a Java implementation.

Ruby implementation:

require 'digest/md5'
digest = Digest::MD5.hexdigest("encrypt this text")

PHP implementation:

<?php
   $str = "Hello";
   echo md5($str);
?>

Java implementation (2 methods for clarity):

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.io.UnsupportedEncodingException

public class MD5 {

public static String digest(String text) {
      throws NoSuchAlgorithmException, UnsupportedEncodingException {
   MessageDigest md = MessageDigest.getInstance("MD5");
   byte[] md5hash = new byte[32];
   md.update(text.getBytes("iso-8859-1"), 0, text.length());
   md5hash = md.digest();
   return convertToHex(md5hash);
}

private static String convertToHex(byte[] b) {
   StringBuilder result = new StringBuilder(32);
   for (int i = 0; i &lt; b.length; i++) {
      result.append(
         Integer.toString( ( b[i] &amp; 0xff ) + 0x100, 16).substring( 1 ));
   }
   return result.toString();
}
}

This isn’t the fastest MD5 implementation, but that isn’t my goal here. I found quite a few implementations when searching, some of which gave results which were not even correct!

Hope this implementation helps someone else.

written by admin \\ tags: , , ,