The HMAC is an algorithm that generates a hash of the message using a cryptographic hash function and a secret cryptographic key. It can be used to check data for integrity and authenticity. It lets us calculate message authenticity and integrity using a shared key between two parties without the use of complex public key infrastructure involving certificates. Python provides us with module name hmac which provides an implementation for this algorithm. It takes as input hashing algorithm name which is one of the algorithms which is available through hashlib library of Python. As a part of this tutorial, we'll explain with simple examples how we can generate message authentication code using hmac module of Python.
Below we have printed names of the algorithms available through hashlib library. If you are interested in learning about hashlib library then please feel free to check our tutorial on the same.
import hashlib
print("List of Available Algorithms to Construct Secure Hash/Message Digest : {}".format(hashlib.algorithms_available))
print("\nList of Algorithms Guaranteed to Work : {}".format(hashlib.algorithms_guaranteed))
print("\nList of Algorithms that May Work : {}".format(hashlib.algorithms_available.difference(hashlib.algorithms_guaranteed)))
As a part of our first example, we'll explain how we can generate a message authentication code of a given message based on the input key and secure hashing algorithm using hmac module.
update(message_bytes) - This method adds messages given as input to already an existing message. We can call this method more than once and it'll keep on adding up messages.
digest() - It returns the message authentication code of the data in bytes format. The size of the output is dependent on the input secure hashing algorithm. For example, if the input hashing algorithm is SHA1, then the output will be 20 bytes.
Our code for this example starts by initializing the message and key. It then generates message authentication code for the given message using key and sha1 algorithm in three different ways.
We first create an instance of HMAC using new() method by giving it key and message as bytes and hashing algorithm name as sha1. We are then printing message authentication code.
Our second part of the code creates the HMAC instance without any initial message. It then uses update() method to add message. At last, it calculates digest and prints it.
Our third part of the code creates an instance of HMAC without any initial message. It then adds messages in two parts using update() method. At last, it calculates digest and prints it.
The code at last prints digest size and block size for each HMAC instance.
import hmac
message = "Welcome to CoderzColumn."
key= "abracadabra"
########## 1 ##################
hmac1 = hmac.new(key=key.encode(), msg=message.encode(), digestmod="sha1")
message_digest1 = hmac1.digest()
print("{} - Message Digest 1 : {}".format(hmac1.name, message_digest1))
########## 2 ##################
hmac2 = hmac.new(key=key.encode(), digestmod="sha1")
hmac2.update(bytes(message, encoding="utf-8"))
message_digest2 = hmac2.digest()
print("{} - Message Digest 2 : {}".format(hmac2.name, message_digest2))
########## 3 ##################
hmac3 = hmac.new(key=key.encode(), digestmod="sha1")
hmac3.update(bytes("Welcome to ", encoding="utf-8"))
hmac3.update(bytes("CoderzColumn.", encoding="utf-8"))
message_digest3 = hmac3.digest()
print("{} - Message Digest 3 : {}".format(hmac3.name, message_digest3))
print("\nMessage Digest Size for 1 : {}, 2 : {} and 3 : {}".format(hmac1.digest_size, hmac2.digest_size,hmac3.digest_size,))
print("Message Block Size for 1 : {}, 2 : {} and 3 : {}".format(hmac1.block_size, hmac2.block_size,hmac3.block_size,))
As a part of our second example, we are explaining how we can calculate message authentication code using HMAC algorithm again but this time we have used SHA256 secure hashing algorithm inside of it.
Our code for this part is exactly the same as our previous example but with minor changes. It uses a reference to SHA256 algorithm available through hashlib library.
import hmac
message = "Welcome to CoderzColumn."
key= "abracadabra"
########## 1 ##################
hmac1 = hmac.new(key=key.encode(), msg=message.encode(), digestmod=hashlib.sha256)
message_digest1 = hmac1.digest()
print("{} - Message Digest 1 : {}".format(hmac1.name, message_digest1))
########## 2 ##################
hmac2 = hmac.new(key=key.encode(), digestmod=hashlib.sha256)
hmac2.update(bytes(message, encoding="utf-8"))
message_digest2 = hmac2.digest()
print("{} - Message Digest 2 : {}".format(hmac2.name, message_digest2))
########## 3 ##################
hmac3 = hmac.new(key=key.encode(), digestmod=hashlib.sha256)
hmac3.update(bytes("Welcome to ", encoding="utf-8"))
hmac3.update(bytes("CoderzColumn.", encoding="utf-8"))
message_digest3 = hmac3.digest()
print("{} - Message Digest 3 : {}".format(hmac3.name, message_digest3))
print("\nMessage Digest Size for 1 : {}, 2 : {} and 3 : {}".format(hmac1.digest_size, hmac2.digest_size,hmac3.digest_size,))
print("Message Block Size for 1 : {}, 2 : {} and 3 : {}".format(hmac1.block_size, hmac2.block_size,hmac3.block_size,))
As a part of our third example, we are explaining how we can generate hex message authentication code using HMAC algorithm with SHA256 as its back end.
Our code for this example is exactly the same as our previous example with the only change that we are calling hexdigest() method to calculate hexadecimal authentication code.
import hmac
message = "Welcome to CoderzColumn."
key= "abracadabra"
########## 1 ##################
hmac1 = hmac.new(key=key.encode(), msg=message.encode(), digestmod=hashlib.sha256)
message_digest1 = hmac1.hexdigest()
print("{} - Hex Message Digest 1 : {}".format(hmac1.name, message_digest1))
########## 2 ##################
hmac2 = hmac.new(key=key.encode(), digestmod=hashlib.sha256)
hmac2.update(bytes(message, encoding="utf-8"))
message_digest2 = hmac2.hexdigest()
print("{} - Hex Message Digest 2 : {}".format(hmac2.name, message_digest2))
########## 3 ##################
hmac3 = hmac.new(key=key.encode(), digestmod=hashlib.sha256)
hmac3.update(bytes("Welcome to ", encoding="utf-8"))
hmac3.update(bytes("CoderzColumn.", encoding="utf-8"))
message_digest3 = hmac3.hexdigest()
print("{} - Hex Message Digest 3 : {}".format(hmac3.name, message_digest3))
print("\nMessage Digest Size for 1 : {}, 2 : {} and 3 : {}".format(hmac1.digest_size, hmac2.digest_size,hmac3.digest_size,))
print("Message Block Size for 1 : {}, 2 : {} and 3 : {}".format(hmac1.block_size, hmac2.block_size,hmac3.block_size,))
As a part of our code, we are explaining how we can generate message authentication code using digest() method of the hmac module without creating an instance of the HMAC.
Our code for this example, explains how we can digest() method to generate message authentication code for the given message using input key directly without creating an instance of HMAC instance like the previous example. This method works fast compared to creating authentication code for small messages through HMAC instance because it uses optimized C implementation for creating digest.
import hmac
message = "Welcome to CoderzColumn."
key= "abracadabra"
########## 1 ##################
message_digest1 = hmac.digest(key=key.encode(), msg=message.encode(), digest="sha3_256")
print("Message Digest 1 : {}".format(message_digest1))
########## 2 ##################
message_digest2 = hmac.digest(key=key.encode(), msg=bytes(message, encoding="utf-8"), digest=hashlib.sha3_256)
print("Message Digest 2 : {}".format(message_digest2))
As a part of our fifth example, we are explaining how we can use compare() method of hmac module to compare message authentication codes.
Our code for this example creates two message authentication codes and compares them using compare() method.
import hmac
message = "Welcome to CoderzColumn."
key= "abracadabra"
########## 1 ##################
message_digest1 = hmac.digest(key=key.encode(), msg=message.encode(), digest="sha3_256")
print("Message Digest 1 : {}".format(message_digest1))
########## 2 ##################
message_digest2 = hmac.digest(key=key.encode(), msg=bytes(message, encoding="utf-8"), digest=hashlib.sha3_256)
print("Message Digest 2 : {}".format(message_digest2))
print("\nIs message digest 1 is equal to message digest 2? : {}".format(hmac.compare_digest(message_digest1, message_digest2)))
This ends our small tutorial explaining how we can create a message authentication code for a given message using hmac module. Please feel free to let us know your views in the comments section.
If you are more comfortable learning through video tutorials then we would recommend that you subscribe to our YouTube channel.
When going through coding examples, it's quite common to have doubts and errors.
If you have doubts about some code examples or are stuck somewhere when trying our code, send us an email at coderzcolumn07@gmail.com. We'll help you or point you in the direction where you can find a solution to your problem.
You can even send us a mail if you are trying something new and need guidance regarding coding. We'll try to respond as soon as possible.
If you want to