1

我想在一个ActionListener类中使用以下代码。

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"and"UTF-8"不能以任何方式导入。当我在控制台程序中执行此操作时,我可以通过以下方式解决此问题:

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

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

4

1 回答 1

1

您事先知道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);
}

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

于 2015-06-08T02:47:00.607 回答