Skip to content
Advertisement

Verify Hashing.sha256() generated hash

I have this code created using Google Guava:

String sha256hex = Hashing.sha256()
                    .hashString(cardNum, StandardCharsets.UTF_8)
                    .toString();

How I can verify the generated values is a properly generated hash?

Advertisement

Answer

SHA-256 and, in general, the family of SHA 2 algorithms is wonderfully described in Wikipedia and different RFCs, RFC 6234 and the superseded RFC 4634.

All these sources dictate that the output provided by the SHA 256 hash function is 256 bits length, 32 bytes (the number that accompanies the SHA word is the mentioned value for every algorithm in the family, roughly speaking).

These sequence of bytes is typically encoded in hex. This is the implementation provided by Guava as well.

Then, the problem can be reduced to identify if a string in Java is a valid hex encoding.

That problem has been already answered here, in SO, for example in this question.

For its simplicity, consider the solution proposed by @laycat:

boolean isHex = mac_addr.matches("^[0-9a-fA-F]+$");

As every byte is encoded with two hex characters and, as mentioned, the SHA-256 algorithm produces and output of 32 bytes you can safely check for a string of 64 characters length, as suggested in the answer of @D.O. as well. Your validation code could be similar to this:

boolean canBeSha256Output = sha256Hex.matches("^[0-9a-fA-F]{64}$");

Please, be aware that there is no possibility for saying if a character hex string of a certain length on its own is or not the result of a hash function, whichever hash function you consider.

You only can be sure that a hash output is a hash output if and only if it matches the result of applying the corresponding hash function over the original input.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement