MessageDigest NoSuchAlgorithmException

前端 未结 3 1477
借酒劲吻你
借酒劲吻你 2021-02-10 15:44

I want to use MessageDigest to get a MD5 hash, but I get an error.

import java.security.MessageDigest;

public class dn {
  public static void main(         


        
相关标签:
3条回答
  • 2021-02-10 16:21

    In addition to other answers here

    Certain algorithms would not be available with some JVM

    To make it truly portable application you should do this

    public boolean isMDAvailable(String s)
    {
        boolean success=true;
        try{MessageDigest.GetInstance(s);}
        catch(NoSuchAlgorithmException x)
        {
             success=false;
        }
        return success;
    }
    

    Now you can get any available MD algorithm with this method

    public MessageDigest getAvailableMessageDigest()
    {
        if(isMDAvailable("MD5")==true)return MessageDigest.GetInstance("MD5");
        else if(isMDAvailable("MD2")==true)return MessageDigest.GetInstance("MD2");
        else if(isMDAvailable("SHA-512")==true)return MessageDigest.GetInstance("SHA-512");
        else return null;
    }
    
    0 讨论(0)
  • 2021-02-10 16:28

    The error message is clear : the code doesn't compile (Unresolved compilation problem) because you're not handling the checked exception NoSuchAlgorithmException that can be thrown by MessageDigest.getInstance().

    Either add this exception to the throws clause of the main method, or catch it:

    public static void main(String[] args) throws NoSuchAlgorithmException {
        ...
    }
    
    or
    
    public static void main(String[] args) {
        try {
            ...
        }
        catch (NoSuchAlgorithmException e) {
            System.err.println("I'm sorry, but MD5 is not a valid message digest algorithm");
        }
    }
    

    Note that this is a compilation error. You chose to launch your program despite the presence of compilation errors (visible in the "Problems" view of Eclipse), and despite the fact that Eclipse warned you about that before launching the program. So you tried executing code which doesn't compile, which you shouldn't do.

    EDIT: fixed the typo in the code in NoSuchAlgorithmException

    0 讨论(0)
  • 2021-02-10 16:28

    You should handle the exception:

    try {
    
       MessageDigest md = MessageDigest.getInstance("MD5");
       //...
    
    } catch(NoSuchAlgorithmException x) {
      // do proper exception handling
    }
    
    0 讨论(0)
提交回复
热议问题