View RSS Feed

My Java Tips

Creating MessageDigest

Rate this Entry
by , 11-07-2011 at 06:42 PM (765 Views)
Message digests are secure one-way hash functions that take arbitrary-sized data and output a fixed-length hash value. Thing to remember is that it I s not any encryption technique. Itís simply hashing. Same message will always generate the same hash code and a slight change in the message will generate completely different hash code. In the next few posts, I will talk about how we can generate message digests in our Java programs.


The popular message digest algorithms are MD5 and SHA. java.security.MessageDigest class provides support for creating message digests. You are not supposed to implement the MD5v or SHA algorithms. MessageDigest class has all the needed implementations.

Lets me show this through an example:

Java Code:
String str = "Hello World";

byte[] defaultBytes = str.getBytes();

MessageDigest algorithm = MessageDigest.getInstance("MD5");
algorithm.reset();
algorithm.update(defaultBytes);
byte messageDigest[] = algorithm.digest();

StringBuffer hexString = new StringBuffer();

for (int i=0;iString hex = Integer.toHexString(0xFF & messageDigest[i]);
if(hex.length()==1)
hexString.append('0');
hexString.append(hex);
}

System.out.println("String:  " + str);
System.out.println("MessageDigest: " + hexString.toString());
Output:

String: Hello World
MessageDigest: b10a8db164e0754105b7a99be72e3fe5




Lets do some experiments. I changed the string slighlty and got entirely different hash code. Review the output:

String: hello World
MessageDigest: 39d11ab1c3c6c9eab3f5b3675f438dbf

You have 3 different methods to generate the digest. Use the one as required.

Java Code:
 byte[] 	digest()
 byte[] 	digest(byte[] input)
 int 	digest(byte[] buf, int offset, int len)
As a developer, you need not to worry about MD5 algorithm implementation. So, generating message digests is very simple and easy.

Submit "Creating MessageDigest" to Facebook Submit "Creating MessageDigest" to Digg Submit "Creating MessageDigest" to del.icio.us Submit "Creating MessageDigest" to StumbleUpon Submit "Creating MessageDigest" to Google

Tags: None Add / Edit Tags
Categories
Java SE

Comments