At times we need to create a one way hash(digest) for a give string/text, there are various algorithm that can be used to do so (MD5,SHA etc.)
The snippet below shows how this can be done.
<!--break-->
package com.livrona.snippets.security;
import java.math.BigInteger;
import java.security.MessageDigest;
/**
* This snippet shows how we can generate the digest MD5
* for a given string. The digest is a one way hash and
* is represented into hex.
*
* @author mvohra
*/
publicclass MD5Generator {
publicstaticvoid main(String args[]) throws Exception {
// string to be encoded
String text ="Hello World";
// get the instances for a given digest scheme MD5 or SHA
MessageDigest m = MessageDigest.getInstance("MD5");
// generate the digest ; pass in the text as bytes,
// length to the bytes(offset) to be hashed; for full string
// pass 0 to text.length()
m.update(text.getBytes(), 0, text.length());
// get the String representation of hash bytes,
// create a big integer out of bytes
// then convert it into hex value (16 as input to toString method)
String digest =new BigInteger(1, m.digest()).toString(16);
System.out.println("MD5: "+ digest);
}
}