gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 08:08:53 25 4
gpt4 key购买 nike

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

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

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

最佳答案

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

关于java - ActionListener 类中的哈希字符串 (SHA-256),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30698734/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com