Thales IoT Developer Community
MD5 hash calculation
Tutorial, February 27, 2014 - 1:24pm, 5100 views
Here are example how to generate MD5 ****es for a String object or byte array.
//The three lines below showing how to use MD5calculator object
String myText = "Give me the MD5 ****"; //input String ****= MD5calculator.getInsance().getHash(myText); //generate the **** System.out.println(****); //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 ****es 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 **** of a byte array * * @param byteBuffer * for this byte array the **** is generated * @return **** 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 // **** (always 16byte for MD5) byte[] md5byte = new byte[16]; // generate the **** int len = msgDigest.digest(md5byte, 0, md5byte.length); // convert **** 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 **** of a String * * @param text * for this String the **** is generated * @return **** as a string in hex format */ public String getHash(String text) { return getHash(text.getBytes()); } }