ActionListener 中的哈希字符串 (SHA-256) class

Hashing String (SHA-256) in an ActionListener class

我想在 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();

但是 "SHA-256""UTF-8" 无法以任何方式导入。当我在控制台程序中执行此操作时,我可以使用以下方法解决此问题:

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

但我不能 ActionListener class。我该如何解决这个问题?

你事先知道 MessageDigest.getInstance("SHA-256")key.getBytes("UTF-8") 会成功,所以最好的解决方案是围绕不可能的检查异常包装一个 try-catch:

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);
}

现在使用此代码,您无需按照合同的要求在 ActionListener 方法上声明 throws