我对涉及基本加密货币的项目有疑问。要求之一是根据文件中提供的哈希检查前一行的哈希。因此,本质上,您将计算上一行的 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;
}