Wednesday 6 August 2014

How to generate MD5 Hash in Java


There are multiple ways to generate MD5 hash in Java Program. Not only Java API provides convenient method to generate MD5 hash, you can also use popular open source frameworks, like Spring and Apache commons Codec to generate MD5 digest in Java.

 MD5 is popular Message Digest Algorithm, which is most commonly used to check data integrity e.g. comparing MD5 check-sum to see, if any file is altered or not. Though, MD5 was not considered a good cryptographic algorithm for security purpose due to several vulnerability found on it, it's still good enough or cheking integrity of file. 


MD5 hashing algorithm generate a 128 bit or 16 byte long hash value. MD5 hash values, also known as MD5 digest is mostly represented as 32 character Hex String. You can generate MD5 hash from a byte array, or String directly using Java, Spring and Apache commons codec. Spring and Apache commons codec has identical API e.g. class name DigestUtils is same and allows you to directly generate MD5 hash as Hex String, while if you use Java than you need to convert byte array to Hex String, as java.security.MessageDigest.digest() method returns MD5 hash as byte array.



Note:  Please remember that once this password hash is generated and stored in database, you can not convert it back to original password. Each time user login into application, you have to regenerate password hash again, and match with hash stored in database. So, if user forgot his/her password, you will have to send him a temporary password and ask him to change it with his new password.

Here, the password to be encoded is often called the “message” and the generated hash value is called the message digest or simply “digest”.


Below is the Simple password security using MD5 algorithm



import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;

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

public class SimpleMD5Example {

    public static void main(String[] args) {
        String passwordToHash = "password";
        md5Java(passwordToHash);
        md5ApacheCommonsCodec(passwordToHash);

    }

    public static void md5Java(String passwordToHash) {

        try {
            // Create MessageDigest instance for MD5
            MessageDigest md = MessageDigest.getInstance("MD5");
            //Add password bytes to digest
            md.update(passwordToHash.getBytes("UTF-8"));
            //Get the hash's bytes
            byte[] bytes = md.digest();
            //This bytes[] has bytes in decimal format;

            //Convert it to hexadecimal format method1
            StringBuilder sb = new StringBuilder();
            for(int i=0; i< bytes.length ;i++)
            {
                sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));
            }
            //Get complete hashed password in hex format
            System.out.println("MD5 hash generated using Java: " +sb.toString());

            //Convert it to hexadecimal format method2
            System.out.println("MD5 hash generated using Java: " +new String(Hex.encodeHex(bytes)));
        }
        catch (NoSuchAlgorithmException e)
        {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

    }

    public static void md5ApacheCommonsCodec(String text) {
        System.out.println("MD5 message created by Apache commons codec: " +DigestUtils.md5Hex(text));
    }



}



OutPut:


MD5 hash generated using Java: 5f4dcc3b5aa765d61d8327deb882cf99
MD5 hash generated using Java: 5f4dcc3b5aa765d61d8327deb882cf99
MD5 message created by Apache commons codec: 5f4dcc3b5aa765d61d8327deb882cf99


No comments:

Post a Comment