close

How to use SHA256-HMAC in python code?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to use SHA256-HMAC in python code in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to use SHA256-HMAC in python code?

  1. How to use SHA256-HMAC in python code?

    For later versions of python, you need a mix of all of the other answers to get the OPs output. The hmac.new function wants the key argument to be of type bytes or bytearray

  2. use SHA256-HMAC in python code

    For later versions of python, you need a mix of all of the other answers to get the OPs output. The hmac.new function wants the key argument to be of type bytes or bytearray

Method 1

You are not making use of hmac at all in your code.

Typical way to use hmac, construct an HMAC object from your key, message and identify the hashing algorithm by passing in its constructor:

h = hmac.new( key, my, hashlib.sha256 )
print( h.hexdigest() )

That should output

adcb671e8e24572464c31e8f9ffc5f638ab302a0b673f72554d3cff96a692740

for your example data.

Method 2

For later versions of python, you need a mix of all of the other answers to get the OPs output. The hmac.new function wants the key argument to be of type bytes or bytearray

TypeError: key: expected bytes or bytearray, but got ‘str’

Even if the key argument were fixed, the hmac.new function would then complain about the my string with the following error:

TypeError: Unicode-objects must be encoded before hashing

import hashlib
import hmac

# my and key as per question
my = "/api/embedded_dashboard?data=%7B%22dashboard%22%3A7863%2C%22embed%22%3A%22v2%22%2C%22filters%22%3A%5B%7B%22name%22%3A%22Filter1%22%2C%22value%22%3A%22value1%22%7D%2C%7B%22name%22%3A%22Filter2%22%2C%22value%22%3A%221234%22%7D%5D%7D"
key = "e179017a-62b0-4996-8a38-e91aa9f1"

# encoding as per other answers
byte_key = bytes(key, 'UTF-8')  # key.encode() would also work in this case
message = my.encode()

# now use the hmac.new function and the hexdigest method
h = hmac.new(byte_key, message, hashlib.sha256).hexdigest()

# print the output
print(h)

The output that this prints is

adcb671e8e24572464c31e8f9ffc5f638ab302a0b673f72554d3cff96a692740

exactly as the OP expected.

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read