This section provides a tutorial example on how to write a sample program to use the java.security.MessageDigest class to digest any input file with the MD5 or SHA message digest algorithm.
The following sample program shows you how to invoke the message digest algorithms
implemented by the default provider, Sun, and digest the data from the input file.
/**
* JcaMessageDigest.java
* Copyright (c) 2002 by Dr. Herong Yang
*/
import java.io.*;
import java.security.*;
class JcaMessageDigest {
public static void main(String[] a) {
if (a.length<3) {
System.out.println("Usage:");
System.out.println("java JcaMessageDigest input output"
+" algorithm");
return;
}
String input = a[0];
String output = a[1];
String algorithm = a[2]; // SHA, MD5
try {
digest(input,output,algorithm);
} catch (Exception e) {
System.out.println("Exception: "+e);
return;
}
}
private static void digest(String input, String output,
String algorithm) throws Exception {
MessageDigest md = MessageDigest.getInstance(algorithm);
System.out.println();
System.out.println("MessageDigest Object Info: ");
System.out.println("Algorithm = "+md.getAlgorithm());
System.out.println("Provider = "+md.getProvider());
System.out.println("Digest Length = "+md.getDigestLength());
System.out.println("toString = "+md.toString());
FileInputStream in = new FileInputStream(input);
int bufSize = 1024;
byte[] buffer = new byte[bufSize];
int n = in.read(buffer,0,bufSize);
int count = 0;
while (n!=-1) {
count += n;
md.update(buffer,0,n);
n = in.read(buffer,0,bufSize);
}
in.close();
FileOutputStream out = new FileOutputStream(output);
byte[] digest = md.digest();
out.write(digest);
out.close();
System.out.println();
System.out.println("Message Digest Processing Info: ");
System.out.println("Number of input bytes = "+count);
System.out.println("Number of output bytes = "+digest.length);
}
}
Here is the result of my first test. It is done with JDK 1.3.1.
javac -classpath . JcaMessageDigest.java
java -cp . JcaMessageDigest JcaMessageDigest.class digest.sha SHA
MessageDigest Object Info:
Algorithm = SHA
Provider = SUN version 1.2
Digest Length = 20
toString = SHA Message Digest from SUN, <initialized>
Message Digest Processing Info:
Number of input bytes = 2060
Number of output bytes = 20
dir *.class *.sha
07:00p 2,060 JcaMessageDigest.class
07:02p 20 digest.sha
The program seems to be working:
Since I am not specifying the provider name,
the implementation of the SHA algorithm provided in the default security package
was selected. Of course, Sun is the provider of the default security package.
The digest length is 20 bytes for the default implementation of the SHA algorithm.
The program reads the input file, JcaMessageDigest.class, into a byte array buffer,
then passes the buffer to the message digest object to process by calling the update().
When the entire input file is processed, digest() method is called to ouptput
the digest data.
The number of bytes reported by the program matches well with the file sizes.