hmac – Keyed-Hashing for Message Authentication


HMAC is a mechanism for message authentication using cryptographic hash functions. HMAC can be used with any iterative cryptographic hash function, e.g., MD5, SHA-1, in combination with a secret shared key.
This module implements the HMAC algorithm. The basic idea is to generate a cryptographic hash of the actual data combined with a shared secret key. The resulting hash can then be used to check the transmitted or stored message to determine a level of trust, without transmitting the secret key.

hmac.new(key, msg=None, digestmod=None)

Return a new hmac object. key is a bytes or bytearray object giving the secret key. If msg is present, the method call update(msg) is made. digestmod is the digest name, digest constructor or module for the HMAC object to use. It supports any name suitable to hashlib.new().

A HMAC object has following methods:

  1. HMAC.update(msg): This method updates the hmac object with msg. Repeated calls are equivalent to a single call with the concatenation of all the arguments: m.update(a); m.update(b) is equivalent to m.update(a + b).
  2. HMAC.digest(): This method returns the digest of the bytes passed to the update() method so far. This bytes object will be the same length as the digest_size of the digest given to the constructor.
  3. HMAC.hexdigest(): This method is like the digest() method except the digest is returned as a string twice the length containing only hexadecimal digits.
  4. HMAC.copy(): This method returns a copy or a clone of the hmac object. This can be used to efficiently compute the digests of strings that share a common initial substring.

A hash object has following attributes:

Example:


# Python 3 code to demonstrate the working of hmac module.

  

import hmac

import hashlib

  

# creating new hmac object using sha1 hash algorithm

digest_maker = hmac.new(b'secret-key', b'msg', hashlib.sha1)

  

# print the Hexdigest of the bytes passed to update

print ("Hexdigest: " + digest_maker.hexdigest())

  

# call update to update msg

digest_maker.update(b'another msg')

  

# print the Hexdigest of the bytes passed to update

print ("Hexdigest after update: " + digest_maker.hexdigest())

  

print ("Digest size: " + str(digest_maker.digest_size) + " bytes")

print ("Block size: " + str(digest_maker.block_size) + " bytes")

print ("Canonical name: " + digest_maker.name)

  

# print the digest of the bytes passed to update

print ("Digest: ", end =" ")

print (digest_maker.digest())

  

# create a copy of the hmac object

digest_clone = digest_maker.copy()

print ("Hexdigest of clone: " + digest_clone.hexdigest())

Output:

Hexdigest: df2ae7cdb5c849001e33ee29eb1c51ba2cafbaa7

Hexdigest after update: 3923273eb3aa9328478eb5aabf2d96e185256b4b

Digest size: 20 bytes

Block size: 64 bytes

Canonical name: hmac-sha1

Digest:  b"9#'>xb3xaax93(Gx8exb5xaaxbf-x96xe1x85%kK"

Hexdigest of clone: 3923273eb3aa9328478eb5aabf2d96e185256b4b