Sunday, July 13, 2008

Java MD5 Hash Sample

MD5 (Message Digest) is an encryption algorithm that creates a unique hash from a given data which is completely reverseble. This means you cannot recalculate original data using its hash , and hash is universally unique.

Here is a sample code that produces MD5 hash of a given string :

  1. package javacream;
  2. import java.security.MessageDigest;
  3. import java.security.NoSuchAlgorithmException;
  4. public class MD5HashTest {
  5.     private static String getMD5Digest(String str) {
  6.         try {
  7.             byte[] buffer = str.getBytes();
  8.             byte[] result = null;
  9.             StringBuffer buf = null;
  10.             MessageDigest md5 = MessageDigest.getInstance("MD5");
  11.             //allocate room for the hash    result = new byte[md5.getDigestLength()];
  12.             //calculate hash    md5.reset();
  13.             md5.update(buffer);
  14.             result = md5.digest();
  15.             System.out.println(result);
  16.             //create hex string from the 16-byte hash    buf = new StringBuffer(result.length * 2);
  17.             for (int i = 0;
  18.             i <
  19.             result.length;
  20.             i++) {
  21.                 int intVal = result[i] & 0xff;
  22.                 if (intVal <
  23.                 0x10) {
  24.                     buf.append("0");
  25.                    
  26.                 }
  27.                 buf.append(Integer.toHexString(intVal).toUpperCase());
  28.                
  29.             }
  30.             return buf.toString();
  31.            
  32.         }
  33.         catch (NoSuchAlgorithmException e) {
  34.             System.err.println("Exception caught: " + e);
  35.             e.printStackTrace();
  36.            
  37.         }
  38.         return null;
  39.        
  40.     }
  41.     public static void main(String[] args) {
  42.         String result = getMD5Digest("This is a text to hash");
  43.         System.out.println("result=" + result);
  44.        
  45.     }
  46.    
  47. }

1 comment:

Anonymous said...

Hey if you want you can also use GrandCentral. It includes the SimpleCrypto class which can generate hashes and checksums using MD5, SHA1, SHA-256, SHA-384 and SHA-512. Just a suggestion. http://code.google.com/p/grandcentral/