Message Digest - MD5 Algorithm
Part:
1
2
3
4
5
(Continued from previous part...)
Step 5. Output. The contents in buffer words A, B, C, D are returned in sequence with
low-order byte first.
MD5 Implementation in Java
Sun provides MD5 algorithm in Java under their JCE (Java Cryptography Extension) package,
which is included in JDK 1.5.
Sun's implementation of MD5 can be accessed through a generic class called MessageDigest.
Here are the main methods of MessageDigest class:
- getInstance("MD5") - Returns a message digest object represents a specific implementation
of MD5 algorithm from the default provider, Sun.
- getProvider() - Returns the provider name of the current object.
- update(bytes) - Updates the input message by appending a byte array at the end.
- digest() - Performs MD5 algorithm on the current input message and returns the message digest
as a byte array. This method also resets the input message to an empty byte string.
- reset() - Resets the input message to an empty byte string.
Here is a sample Java program to show you how to use the MessageDigest class to perform some tests
on MD5 algorithms.
/**
* JceMd5Test.java
* Copyright (c) 2006 by Dr. Herong Yang, http://www.herongyang.com/
*/
import java.security.*;
class JceMd5Test {
public static void main(String[] a) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
System.out.println("Message digest object info: ");
System.out.println(" Algorithm = "+md.getAlgorithm());
System.out.println(" Provider = "+md.getProvider());
System.out.println(" toString = "+md.toString());
String input = "";
md.update(input.getBytes());
byte[] output = md.digest();
System.out.println();
System.out.println("MD5(\""+input+"\") =");
System.out.println(" "+bytesToHex(output));
input = "abc";
md.update(input.getBytes());
output = md.digest();
System.out.println();
System.out.println("MD5(\""+input+"\") =");
System.out.println(" "+bytesToHex(output));
input = "abcdefghijklmnopqrstuvwxyz";
md.update(input.getBytes());
output = md.digest();
System.out.println();
System.out.println("MD5(\""+input+"\") =");
System.out.println(" "+bytesToHex(output));
} catch (Exception e) {
System.out.println("Exception: "+e);
}
}
public static String bytesToHex(byte[] b) {
char hexDigit[] = {'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
StringBuffer buf = new StringBuffer();
for (int j=0; j<b.length; j++) {
buf.append(hexDigit[(b[j] >> 4) & 0x0f]);
buf.append(hexDigit[b[j] & 0x0f]);
}
return buf.toString();
}
}
(Continued on next part...)
Part:
1
2
3
4
5
|