Java SHA-256 哈希与预期输出不匹配



我遇到了一个涉及基本加密货币的项目的问题。其中一个要求是根据文件中提供的哈希检查前一行的哈希。因此,从本质上讲,您将计算上一行的 SHA-256 哈希,与提供的哈希进行比较,如果未提供有效哈希,则引发异常。

但是,我收到一个错误,我已将其缩小到实际的哈希代码。据我所知,我已经验证了该文件是否正确读取,但是一旦该方法将byte[]计算哈希转换为提供的哈希,它就会发现它们不等效并引发异常。我一直在尝试调试,但真的不确定问题出在哪里。

我的代码如下。谢谢!

if (block_line == null && block_hash == "0")
{
return true;         //genesis block, special hash
}
//remove new lines and tabs
block_line = block_line.replaceAll("\r\n", "");
byte[] hash = null;
byte[] file_hash = block_hash.getBytes();
try
{
//create SHA-256 hash of raw line to ensure following hash is correct
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(block_line.getBytes());
hash = md.digest();
}
catch (NoSuchAlgorithmException nsaex)
{
System.err.println("No SHA-256 algorithm found.");
System.err.println("This generally should not happen...");
System.exit(1);
}
//check if the hash in the file was valid for the line in question
try
{
if (Arrays.equals(hash, file_hash))
{
return true;         //file hash is valid
}
else
{
throw new InvalidDataException(block_hash, 0);
}
}
catch (InvalidDataException ide)
{
System.err.println("InvalidDataException: " + ide);
ide.printStackTrace();
System.err.println("Quitting...");
return false;
}

block_hash似乎可能包含十六进制(或可能是以 64 为基数(的编码摘要值。使用getBytes你只会得到该字符串的标准编码:它不会解码十六进制或基数 64。比较字节数组时,会将二进制hash值与包含编码摘要的二进制file_hash进行比较。因此,比较将失败(如果只是因为摘要的大小不同(。

下次输入日志语句或println语句并打印出十六进制哈希,以便您可以用肉眼比较它们。

最新更新