Earlier we have seen a briefing about hash code in Python. Now we will see little more, especialy about MD5 hash code generation algorithm in Python’s hashlib module. To start with, let us see a simple example on how to use hashlib and it’s methods for MD5 hash generation.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | import hashlib # initialize a string str = "www.MyTecBits.com" # encode the string encoded_str = str .encode() # create a md5 hash object initialized with the encoded string hash_obj = hashlib.md5(encoded_str) # convert the hash object to a hexadecimal value hexa_value = hash_obj.hexdigest() # print print ( "\n" , hexa_value, "\n" ) |
Output:
1 | 36015e81e9d1cfc6e330c85356e5abf0 |
The compact version of the above code:
1 2 3 4 | >>> import hashlib >>> hashlib.md5(b "www.MyTecBits.com" ).hexdigest() '36015e81e9d1cfc6e330c85356e5abf0' >>> |
Now let us see the other commonly used options available in md5 hashing.
Hash code in byte
As you have noticed, the above example returned the hash code as a hexadecimal value using the hexdigest() method. If you need to get the resultant hash code in byte value, then use the digest() method. Here is an example.
1 2 3 4 | >>> import hashlib >>> hashlib.md5(b "www.MyTecBits.com" ).digest() b '6\x01^\x81\xe9\xd1\xcf\xc6\xe30\xc8SV\xe5\xab\xf0' >>> |
Using update()
In the earlier examples we have created the hash object initialized with the encoded string or byte string. There is another way to append the byte string to the hash object using update() method. You can use the update() multiple times to append the byte string or any other byte date. This method comes in handy when you want to append date to the hash object based on multiple conditions. Here is an example.
1 2 3 4 5 6 7 8 9 10 11 | import hashlib # create a md5 hash object hash_object = hashlib.md5() # append the byte string hash_object.update(b "www." ) hash_object.update(b "MyTecBits" ) hash_object.update(b ".com" ) print ( "\n" , hash_object.hexdigest(), "\n" ) |
Output:
1 | 36015e81e9d1cfc6e330c85356e5abf0 |
Reference
- Online MD5 hash code generator at MyTecBits Tools sction.
- More about hashlib library at Pytho docs.