Keyed Hash for Message Authentication using Python

PythonServer Side ProgrammingProgramming

The HMAC is a framework, it is used to message authentication using cryptographic hash functions. HMAC can be used for MD5, SHA-1 etc.

The basic idea to generate cryptographic hash, is perform the hashing on the actual data and secret key. The final output is sent without the secret key.

To use this module, we need to import the hmac module in the python code.

import hmac

Some methods and attributes of the hmac module are as follows −

Method hmac.update(message)

This method is used to update the hmac object with the given message. Repeated call of this function is equivalent with the single call with concatenated arguments.

Method hmac.digest()

This method is used to return the digested data which is passed through the update method. The size of the byte object is same as the digest_size. It may contain bytes in the whole range from 0 to 255.

Method hashlib.hexdigest()

This method is same as the digest method but the result will contain only hexadecimal values. This method is used to send data through the internet very easily.

Method hashlib.copy()

This method is used to make a copy of the hmac object. To compute the digest of strings in a more efficient way, the copy() method is useful.

Example Code

import hashlib
import hmac
update_bytes = b'Python123'
password = b'abcde1234'
my_hmac = hmac.new(update_bytes, password, hashlib.md5) #Create hash using md5 algorithm
print("The first digest: " + str(my_hmac.digest()))
print("The Canonical Name: " + my_hmac.name)
my_hmac_cpy = my_hmac.copy() #Create a copy of the hmac object
print("The Copied digest: " + str(my_hmac_cpy.digest()))

Output

The first digest: b"\x1c\xe1\xfb\x9b\xd4\x8bu\xb9\xe6N6\xee\x00O'}"
The Canonical Name: hmac-md5
The Copied digest: b"\x1c\xe1\xfb\x9b\xd4\x8bu\xb9\xe6N6\xee\x00O'}"
raja
Published on 31-Oct-2018 12:11:13
Advertisements