Wednesday, September 14, 2011

MD5 encryption in Java

What is MD5?
MD5(Message-Digest algorithm 5)is hashing function which results in 128 bit(16 byte) hash value. It came as a replacement of MD4 which was considered insecure then. MD5 is one way encryption technique means once I have encrypted some text using MD5 I cannot get the clear text from the hash value again. But now it is proved that even MD5 is vulnerable.

Where can we use MD5?
MD5 can primarily be used for encryption and for checking file integrity. But again remember it is possible to have two big different files having same hash value.
Usage examples:
  1. Data Encryption:You can use it to encrypt your passwords something like getMD5Hash(password+date+time of registration)= 'hashed value'. Here we have concatenated actual passwords with date and time of registration to ensure that every time a unique hash value gets generated.
  2. File integrity: Suppose you want to make a file comparing utility. So if you will go straight away and compare the files it will not efficient. So first we can compare size, then HASH VALUE OF BOTH FILES(by using MD5 hashing) and if both are same then probably you can compare the actual text in the files.

Implementing MD5 in Java:
MD5 is already implemented in java. So we just need to reuse the method and do some pre and post processing. MD5 hashing technique always produces a fixed length encrypted string having 128 bits or 16 bytes and so you will always get a hexadecimal string of length 16.
Code listing is given below:
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;

/**
 * @author dharmvir.singh
 * @Description: This class generated the hash code of few strings
 * 
 */
public class TestMD5 {
 public static void main(String[] args) {
  String[] inputStrings = { "Open Source", "Apache project",
    "java espresso" };
  System.out.println("String\t\t\tHash Value\t\tHash val length");
  System.out.println("======\t\t\t==========\t\t===============");
  for (int i = 0; i < inputStrings.length; i++) {
   System.out.println(inputStrings[i] + "\t\t"
     + getMD5HashVal(inputStrings[i]));
  }
 }

 public static String getMD5HashVal(String strToBeEncrypted) {
  String encryptedString = null;
  byte[] bytesToBeEncrypted;
  try {
   // convert string to bytes using a encoding scheme
   bytesToBeEncrypted = strToBeEncrypted.getBytes("UTF-8");
   MessageDigest md = MessageDigest.getInstance("MD5");
   byte[] theDigest = md.digest(bytesToBeEncrypted);
                        // convert each byte to a hexadecimal digit
   Formatter formatter = new Formatter();
   for (byte b : theDigest) {
    formatter.format("%02x", b);
   }
   encryptedString = formatter.toString().toLowerCase();

  } catch (UnsupportedEncodingException e) {
   e.printStackTrace();
  } catch (NoSuchAlgorithmException e) {
   e.printStackTrace();
  }
  return encryptedString;
 }
}
The code is self explanatory and I tested it already. For production purposes, avoid using MD5 as encryption technique for banking domain and (security concerned) domains.
Related Articles
Implementing DES in Java

Relevant References JBuilder Professional: Pure Java Visual Development With Integrated Database Tools

5 comments:

  1. Why should it be avoided? The article really does not explain.

    ReplyDelete
  2. Because MD5 hash can be broken... easily by hackers as the key size is very small just 16bytes.. for us it will seem to be ok.. check out the MD5 details on wiki... You can use SHA-1 which uses 160 bit key... so more secure..
    For MD5 problems check the link below..


    Wiki: MD5 Security Compromised.

    ReplyDelete
  3. Can I get the program in java for sending TCP Header

    ReplyDelete
  4. SHA-1 is now compromised too. So move on to SHA-2. No collisions for SHA-1 though. Best theoretical attack 2^51.

    ReplyDelete
  5. I was trying to perform the same implementation. But the code which I wrote was not accurate as when I tested it so many errors were encountered. I am lucky that I found this article. Thanks to you.
    electronic signature software

    ReplyDelete