【问题标题】:Java SHA-256 Program provides wrong HashJava SHA-256 程序提供了错误的哈希
【发布时间】:2020-06-29 05:01:20
【问题描述】:

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

    }
}

这是一个失败的测试用例。

【问题讨论】:

  • 有助于了解预期的答案/结果应该是什么......
  • 在图片中可以看到程序的预期输出

标签: java java-7 sha256 cryptographic-hash-function


【解决方案1】:

一个 32 字节的哈希表示一个 64 个字符的字符串。每个字节包含 2 个十六进制数字,因此每个字节需要 2 个字符:

while (hexString.length() < 64)  
{  
    hexString.insert(0, '0');  
}  

【讨论】:

    猜你喜欢
    • 2014-08-19
    • 2023-03-18
    • 1970-01-01
    • 2013-01-09
    • 2017-09-20
    • 2012-11-19
    • 2011-03-07
    • 2010-12-17
    • 2016-02-03
    相关资源
    最近更新 更多