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.
Throwables.propagate
, which is not too bad, but still.) – Tidewater