By submitting your information, you agree that jguru.com may send you jGuru offers via email, phone and text message, as well as email offers about other products and services that jGuru believes may be of interest to you. jGuru will process your information in accordance with the Quinstreet Privacy Policy.

How do I work with message digests?

Get the message content as a byte[]. If coming from a file, read bytes from FileInputStream into ByteArrayOutputStream. Other sources would use similar methods, but remember to not treat content as characters.

Get a MessageDigest for the appropriate algorithm. The JDK provides implementations of SHA-1 (or SHA, from NIST FIPS 180-1) and MD5 (from MIT, algorithm RSA-MD5, as defined by RSA DSI in RFC 1321). If you request an algorithm where no provider is available, NoSuchAlgorithmException is thrown. The SHA algorithm results in a 20-byte digest, while MD5 is 16 bytes long.

MessageDigest algorithm =
MessageDigest.getInstance("SHA-1");

or

MessageDigest algorithm =
MessageDigest.getInstance("MD5");

Ensure the digest's buffer is empty. This isn't necessary the first time used. However, it is good practice to always empty the buffer out in case you later reuse it.

algorithm.reset();

Fill the digest's buffer with data to compute a message digest from.

algorithm.update(buffer);

Generate the digest. This does any necessary padding required by the algorithm.

byte[] digest = algorithm.digest();

Save or print digest bytes. If you happen to use Integer.toHexString(), remember that this doesn't print leading zeros.