我在涉及基本加密貨幣的項目中遇到問題。要求之一是根據文件中提供的散列檢查前一行的散列。因此,本質上,您將計算前一行的 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; }
1 回答

萬千封印
TA貢獻1891條經驗 獲得超3個贊
似乎block_hash
包含十六進制編碼的摘要值(或可能是基數 64)。使用getBytes
您只需獲得該字符串的標準編碼:它不會解碼十六進制或基數 64。當您比較字節數組時,二進制hash
值將與file_hash
包含編碼摘要的二進制值進行比較。因此比較將失?。ㄈ绻麅H僅是因為摘要的大小不同)。
下次輸入日志語句或println
語句并打印出十六進制哈希值,以便您可以通過肉眼進行比較。
添加回答
舉報
0/150
提交
取消