HASHLIB: Using HASH functions MD5 and SHA256

 

The usage of hash functions in python is quite simple. Basically we can use the native library hashlib, which give us the possibly to create message digest based on several algorithms, such as MD5 or SHA256. Using this library we may create a hash of some content and then retrieve its binary output or transform that in hexadecimal strings to easy the data transfer in different medias.

The library can be imported with the following instruction:

import hashlib

 

If you want to encode strings, it is necessary to encode that with UTF-8, and it can be done using the encode method of a string object:

myPassword="python3.x"
myPasswordEncoded=myPassword.encode('utf-8')

 

 

 

Then, the hashlib module has a md5 function which receives as parameter the the we would like to generate the hash. And then return the hash object.

hashObject=hashlib.md5(myPasswordEncoded)

 

The hashObject already contains the hash content, and we can retrieve that easily, including several metadata. Some examples are given here:

hashDigest=hashObject.digest()  #bytes object
hashHexa=hashObject.hexdigest() #string object
print("MD5(Digest):",hashDigest)
print("MD5(Hexa):",hashHexa)
print("Hexa length: ", len(hashHexa))
print("Bytes: ", hashObject.digest_size, "Bits", hashObject.digest_size*8)

 

The digest() returns the binary content of the hash. The hexdigest() return that as a string using the hexadecimal format. And the digest_size is an attribute that returns the hash size in bytes.

We can do the same for SHA256 method, using the code below:

print("######## SHA 256 ########")
sha256 = hashlib.sha256()
sha256.update(myPasswordEncoded)
sha256Digest=sha256.digest()
#bytes object
print("SHA 256(Digest)",sha256Digest)
print ("SHA 256(Hexa):", sha256.hexdigest())
print("Hexa length: ", len(sha256.hexdigest())) #string object
print("Bytes: ", sha256.digest_size, "Bits", sha256.digest_size*8)

 

You may download the whole source code here:

 https://github.com/rafaelqg/code/blob/main/hashlib.py


You may watch a video class here:



Comments

Popular posts from this blog

Dart/Flutter: exception handling

Android – SearchView: Adding a Search component direct on your APP menu.

JSON conversion: Built-in functions to convert a string in JSON format to a python object