View RSS Feed

My Java Tips

Creating MessageDigest

Rate this Entry
by , 11-07-2011 at 07:42 PM (1225 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. 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");
byte messageDigest[] = algorithm.digest();

StringBuffer hexString = new StringBuffer();

for (int i=0;iString hex = Integer.toHexString(0xFF & messageDigest[i]);

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

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 Submit "Creating MessageDigest" to StumbleUpon Submit "Creating MessageDigest" to Google

Tags: None Add / Edit Tags
Java SE