Question

In Java, if I want to compute an MD5 sum, I need to be aware of possible exceptions:

try {
   MessageDigest md = MessageDigest.getInstance("MD5");
   // Do stuff
} catch (NoSuchAlgorithmException e) {
   // Can't happen...
}

However, according to the JVM spec, MD5 must be supported, so the exception should never be thrown. Is there a different access pattern that allows me to write more elegant code?

Was it helpful?

Solution

You could forget the Java implementation and use Guava's: http://docs.guava-libraries.googlecode.com/git-history/v11.0/javadoc/com/google/common/hash/Hashing.html#md5() . In Java you can't totally ignore a Checked Exception. You either catch it, or decorate your method with "throws Exception", or get a Library that isn't so pedantic. To me, the Guava variant below reads gets the job done with the least amount of ceremony client surprise.

// Its my problem, yuk...
public byte[] md5TheHardWay( String s ) {
    try {
        MessageDigest md = MessageDigest.getInstance( "MD5" );
        // Do stuff
        byte[] result = md.digest( s.getBytes() );
        return result;
    } catch ( NoSuchAlgorithmException e ) {
        // Can't happen...
        e.printStackTrace();
    }
    return null;
}

// Its your problem, yuk...
public byte[] md5ItsYourProblemClient( String s ) throws NoSuchAlgorithmException {
    MessageDigest md = MessageDigest.getInstance( "MD5" );
    // Do stuff
    byte[] result = md.digest( s.getBytes() );
    return result;
}

// Its no problem...I like Guava.
public byte[] md5ThroughGuava( String s ) {
    HashFunction md = Hashing.md5();
    HashCode code = md.hashBytes( s.getBytes() );
    return code.asBytes();
}

Surfing through the Guava code it is interesting how they do this. For all intents and purposes, the Guava library writer went the "Its my problem, yuk..." path, caught the checked exception, and turned it into a RuntimeException. Clever and effective.

// an excerpt from the Guava sourcecode
private static MessageDigest getMessageDigest(String algorithmName) {
  try {
    return MessageDigest.getInstance(algorithmName);
  } catch (NoSuchAlgorithmException e) {
    throw new AssertionError(e);
  }
}

Have I mentioned I love Guava? I love Guava.

OTHER TIPS

Instead of MessageDigest you can use common.apache DigestUtils. This is easy to use and no need to take such long procedure to digest data like MessageDigest does.

DigestUtils.md5("String to digest");

Go through this Class and follow this documentation

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top