Hashing String (SHA-256) in an ActionListener class

137 views Asked by At

I want to use the following code in an ActionListener class.

MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(key.getBytes("UTF-8"));

BigInteger HashValue = new BigInteger(javax.xml.bind.DatatypeConverter.printHexBinary(hash).toLowerCase(), 16);
String HashValueString = HashValue.toString();

But the "SHA-256" and "UTF-8" can't be imported in any way. When I do this in a console program, I can solve this with:

public static void main(String[] args) throws NoSuchAlgorithmException, UnsupportedEncodingException 

But I can't in an ActionListener class. How can I solve this?

1

There are 1 answers

0
Nayuki On BEST ANSWER

You know in advance that MessageDigest.getInstance("SHA-256") and key.getBytes("UTF-8") will succeed, so the best solution is to wrap a try-catch around the impossible checked exceptions:

try {
    MessageDigest digest = MessageDigest.getInstance("SHA-256");
    byte[] hash = digest.digest(key.getBytes("UTF-8"));
    BigInteger HashValue = new BigInteger(javax.xml.bind.DatatypeConverter.printHexBinary(hash).toLowerCase(), 16);
    String HashValueString = HashValue.toString();
    // ... The rest of your code goes here ....

} catch (NoSuchAlgorithmException e) {
    throw new AssertionError(e);
} catch (UnsupportedEncodingException e) {
    throw new AssertionError(e);
}

Now with this code, you do not declare a throws on your ActionListener method, as required by the contract.