In this tutorial we are going to learn how to use the SHA-256 algorithm to compute the digest of a message, using Python 3.7.2 and the PyCryptodome module.
pip install pycryptodome
For the documentation about the SHA-256 features supported by the library, please check here.
The SHA-256 is a cryptographic hash function that produces a message digest of 256 bits .
The first thing we will do is importing the SHA256 module from the pycryptodome library.
from Crypto.Hash import SHA256
Optionally, we can pass as input of the new function the data to be hashed. Nonetheless, we can also call the function without any parameters and pass the data later by calling a method on our object. We will follow this second approach.
hashObject = SHA256.new()
Now, to specify the message to be hashed, we simply call the update method on our A256Hash object. As input, we need to pass the message we want to hash as a byte string or a byte array. We will pass it as a byte string.
To later confirm if the obtained message digest is correct, we are going to use this online tool to get the digest of the message in hexadecimal format. We will define a variable with the result.
expectedDigest = "648246ee43bdfc84da50120d50ee57fd88206cebc65db477fbe683d4aacfa1e7"
To obtain the message digest, we can use digest method, which returns the binary digest of the hashed message. Nonetheless, this will return it in a bytes format that is not so easy to interpret for us.
So, we will instead use the hexdigest method. This method returns the digest of the hashed message as a string, in hexadecimal format (lowercase). We can directly print it to the prompt.
Additionally, we will compare the digest against the one we expect (obtained from the online tool). Since both are represented as lower case hexadecimal strings, we can do a direct comparison and print the result.
print (hashObject.hexdigest() == expectedDigest)
The final code can be seen below.
from Crypto.Hash import SHA256 hashObject = SHA256.new() hashObject.update(b'TechTutorialsX') expectedDigest = "648246ee43bdfc84da50120d50ee57fd88206cebc65db477fbe683d4aacfa1e7" print (hashObject.hexdigest()) print (hashObject.hexdigest() == expectedDigest)
Testing the code
To test the previous code, run it in a tool of your choice. I’ll be running it on IDLE.
You should get a result similar to figure 1. As can be seen, we have obtained the digest in hexadecimal format and it matches the one obtained with the online tool.