4
import java.security.*;

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

fails with NoSuchAlgorithm exception.

MessageDigest docs](http://docs.oracle.com/javase/7/docs/api/java/security/MessageDigest.html) say:

Every implementation of the Java platform is required to support the following standard MessageDigest algorithms: MD5 SHA-1 SHA-256 These algorithms are described in the MessageDigest section of the Java Cryptography Architecture Standard Algorithm Name Documentation. Consult the release documentation for your implementation to see if any other algorithms are supported.

So how come it throws the exception?

luckily

import org.apache.commons.codec.digest.DigestUtils;

System.out.println( "md5 = "+DigestUtils.md5Hex( string ) );    

works perfectly, plus it is elegant, but still looks like a pretty basic failure. What am I missing?

jww
  • 97,681
  • 90
  • 411
  • 885

1 Answers1

-3

I have just examined DigestUtils class , there is a try-catch handle for NoSuchAlgorithmException.

You can check in here.

You are missing throws declaration or try-catch block to handle exception. The error should be compilation error. If it's not a compilation error check the "MD5" string typo.

For compilation error , Try to surrond your code with try-catch block.

try {
    MessageDigest md = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {  
    e.printStackTrace();
}

Or add your method throws declaration.

public static void main(String[] args) throws NoSuchAlgorithmException {
İlker Korkut
  • 3,129
  • 3
  • 30
  • 51
  • It's smart from DigestUtils to prepare for a somebody picking a wrong one or making a typo. My riddle is how come this exception is thrown while according the java docs having "MD5" is obligatory. Will it return a correct instance even if it throws the exception? I have no problem with try catch block, just the exception is strange signaling that an obligatory functionality doesn't exist. Is this exception meaningless? – user3795282 Dec 22 '14 at 23:50
  • This exception isn't meaningless, MessageDigest.getInstance() method will will not return an instance if throws exception. http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/security/MessageDigest.java#143 , you may take a look in source code. – İlker Korkut Dec 23 '14 at 00:25
  • @İlkerKorkut The OP was not asking about how to handle exceptions, they were asking about why this exception was being thrown in the first place. However, you've got one thing quite right: case matters, and spelling it "MD5" should clear things up. – Jon Kiparsky Dec 23 '14 at 02:17
  • Yes you are right, but then the question seems not clear. I assumed "MD5" typo was right. – İlker Korkut Dec 23 '14 at 07:24