我正在解决 Hackerrank.com 上的挑战,并且遇到了有关 java SHA-256 加密哈希函数的挑战。 here
我编写了以下代码作为解决方案。但有些测试用例对于我的解决方案来说是失败的。希望知道我的代码有什么问题。
public class Solution {
public static String toHexString(byte[] hash)
{
BigInteger number = new BigInteger(1, hash);
StringBuilder hexString = new StringBuilder(number.toString(16));
while (hexString.length() < 32)
{
hexString.insert(0, '0');
}
return hexString.toString();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input = sc.next();
try
{
MessageDigest md = MessageDigest.getInstance("SHA-256");
System.out.println(toHexString(md.digest(input.getBytes(StandardCharsets.UTF_8))));
}
// For specifying wrong message digest algorithms
catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
}
最佳答案
32 字节哈希表示 64 个字符的字符串。每个字节包含 2 个十六进制数字,因此每个字节需要 2 个字符:
while (hexString.length() < 64)
{
hexString.insert(0, '0');
}
关于Java SHA-256 程序提供错误的哈希值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60733818/