Search code examples
javacryptographyshacryptocurrency

Java SHA-256 Hash Not Matching Expected Output


I'm having an issue with a project involving a basic cryptocurrency. One of the requirements is to check the hash of a previous line against the hash provided in a file. So essentially, you will compute the SHA-256 hash of the previous line, compare to the hash provided, and throw an exception if the valid hash was not provided.

I'm getting an error, however, and I've narrowed it down to the actual hashing code. I've verified that the file is being read in correctly, as far as I can tell, but once the method comes that converts the byte[] computed hash to the provided hash, it finds them not equivalent and throws an exception. I've been trying to debug but am really not sure where the issue is.

My code is below. Thanks!

 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;
 }

Solution

  • It seems likely that the block_hash contains an encoded digest value in hexadecimals (or possibly base 64). Using getBytes you just get the standard encoding of that string: it doesn't decode the hex or base 64. When you compare the byte arrays then the binary hash value is compared with the binary file_hash containing the encoded digest. Therefore the comparison will fail (if just because the digests will be of different sizes).

    Next time put in a log statement or println statement and print out the hexadecimal hashes so you can compare them by eye.