简体   繁体   English

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

[英]Hashing String (SHA-256) in an ActionListener class

I want to use the following code in an ActionListener class. 我想在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();

But the "SHA-256" and "UTF-8" can't be imported in any way. 但是"SHA-256""UTF-8"不能以任何方式导入。 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. 但是我不能在ActionListener类中。 How can I solve this? 我该如何解决?

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: 您已经预先知道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);
}

Now with this code, you do not declare a throws on your ActionListener method, as required by the contract. 现在,使用此代码,您无需按合同要求在ActionListener方法上声明throws

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM