0

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

1 回答 1

0

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

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

于 2018-09-23T01:39:17.367 回答