JDK (Java Development Kit) Tutorials
Dr. Herong Yang, Version 5.00

Comparing Message Digest Output of MD5 and SHA

This section a tutorial example on how to view and compare message digest output from two standard message digest algorithms MD5 and SHA.

The message digest output file contains binary data, which can not be viewed directly. In order to see the digest data, I need to use my other program, HexWriter.java, to convert binary data to hex numbers. See chapter "Encoding Conversion" for details.

Here is how to look at the digest data in hex numbers, 16 bytes per line:

javac HexWriter.java

java -cp . HexWriter digest.sha digest_sha.hex

type digest_sha.hex
9E6BA180ED152D8F58A4C9F33161DE2A
4F9B304A

My second test is to see the digest data of the same input data, JcaMessageDigest.class, using MD5 algorithm:

java -cp . JcaMessageDigest JcaMessageDigest.class digest.md5 MD5

MessageDigest Object Info:
Algorithm = MD5
Provider = SUN version 1.2
Digest Length = 16
toString = MD5 Message Digest from SUN, <initialized>

Message Digest Processing Info:
Number of input bytes = 2060
Number of output bytes = 16

java -cp . HexWriter digest.md5 digest_md5.hex

type digest_md5.hex
CADFA031B79763775D861878062ACA4F

My third test is to see how the digest data changes if I add one byte to the input data:

copy con dot.tmp
.^Z

type dot.tmp >> JcaMessageDigest.class

java -cp . JcaMessageDigest JcaMessageDigest.class digest_1.md5 MD5

MessageDigest Object Info:
Algorithm = MD5
Provider = SUN version 1.2
Digest Length = 16
toString = MD5 Message Digest from SUN, <initialized>

Message Digest Processing Info:
Number of input bytes = 2061
Number of output bytes = 16

java -cp . HexWriter digest_1.md5 digest_1_md5.hex

type digest_1_md5.hex
7772FF57E50B447FE979CAE36C520206

A couple of interesting notes here:

  • The first command is a special trick I learned from DOS system. It allows you to enter data into a file directly from keyboard without using any editor. In the command, "con" is used as a special file name to represent the console, keyboard and monitor. When entering data from keyboard, Control-Z must be used to simulate the end-of-file sign.
  • The second command adds the one-byte file, dot.tmp, to the end of the class file, JcaMessageDigest.class.
  • The third command generates MD5 digest data from the modified class file. The new digest data is very different than old digest data.
  • One surprise is that the modified class file is still working! Why JVM is not checking the class file?

Last update: 2002.

Sections in This Chapter

java.security.MessageDigest - Message Digest MD5 and SHA

JcaMessageDigest.java - Message Digest Sample Program

Comparing Message Digest Output of MD5 and SHA

Dr. Herong Yang, updated in 2008
Comparing Message Digest Output of MD5 and SHA