Gemalto is now part of the Thales Group, find out more.

You are here

MD5 hash calculation

Tutorial, February 27, 2014 - 1:24pm, 2493 views

Here are example how to generate MD5 hashes for a String object or byte array.

//The three lines below showing how to use MD5calculator object

String myText = "Give me the MD5 hash"; //input

String hash= MD5calculator.getInsance().getHash(myText); //generate the hash

System.out.println(hash); //print out the result

//the MD5 calculator class

import java.security.DigestException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * The MD5 calculator provides the possibility to generate hashes of byte arrays
 * or text strings based on the JSR177.
 * 
 * @author markus enck
 * 
 */
public class MD5calculator {

	private static MD5calculator m = new MD5calculator();
	private MessageDigest msgDigest = null;
	private StringBuffer hexStringBuffer;

	/**
	 * 
	 * @return An instance of this object
	 */
	public static synchronized MD5calculator getInsance() {
		return m;
	}

	
	 //singleton construct
	 
	private MD5calculator() {
		try {
			msgDigest = MessageDigest.getInstance("MD5"); // get a MD5 instance
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Calculate the hash of a byte array
	 * 
	 * @param byteBuffer
	 *            for this byte array the hash is generated
	 * @return hash as a string in hex format
	 */
	public String getHash(byte[] byteBuffer) {
		try {
			msgDigest.reset();
			// load the text
			msgDigest.update(byteBuffer, 0, byteBuffer.length);
			// generate a byte array for the MD5
			// hash (always 16byte for MD5)
			byte[] md5byte = new byte[16];
			// generate the hash
			int len = msgDigest.digest(md5byte, 0, md5byte.length);
			// convert hash byte to hex String
			hexStringBuffer = new StringBuffer();
			for (int i = 0; i < len; i++) {
				String hex = Integer.toHexString(0xFF & md5byte[i]); // filter
																		// mask
				// add a zero if one digit only
				if (hex.length() == 1)
					hexStringBuffer.append('0');
				hexStringBuffer.append(hex);
			}
		} catch (DigestException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return hexStringBuffer.toString();
	}

	/**
	 * Calculate the hash of a String
	 * 
	 * @param text
	 *            for this String the hash is generated
	 * @return hash as a string in hex format
	 */
	public String getHash(String text) {
		return getHash(text.getBytes());
	}

}

 
Markus