Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Generate HMAC-SHA1 Signature using Python 3
import hashlib
import hmac
import base64
def make_digest(message, key):
key = bytes(key, 'UTF-8')
message = bytes(message, 'UTF-8')
digester = hmac.new(key, message, hashlib.sha1)
#signature1 = digester.hexdigest()
signature1 = digester.digest()
#print(signature1)
#signature2 = base64.urlsafe_b64encode(bytes(signature1, 'UTF-8'))
signature2 = base64.urlsafe_b64encode(signature1)
#print(signature2)
return str(signature2, 'UTF-8')
result = make_digest('message', 'private-key')
print(result)
@yamyamyuo
Copy link

yamyamyuo commented Feb 24, 2018

why does the key and message has to be bytes in python 3, while in python 2, it requires str

@kneufeld
Copy link

kneufeld commented Mar 3, 2018

Thanks so much for this! However, I needed to call base64.standard_b64encode to make this work.

@klogan12
Copy link

klogan12 commented Jul 30, 2018

I think python3 does not want to handle encoding/decoding taking str as input.
Below is the implementation... And base64.standard_b64encode helped.

def __init__(self, key, msg = None, digestmod = None):
    """Create a new HMAC object.

    key:       key for the keyed hash object.
    msg:       Initial input for the hash, if provided.
    digestmod: A module supporting PEP 247.  *OR*
               A hashlib constructor returning a new hash object. *OR*
               A hash name suitable for hashlib.new().
               Defaults to hashlib.md5.
               Implicit default to hashlib.md5 is deprecated and will be
               removed in Python 3.6.

    Note: key and msg must be a bytes or bytearray objects.
    """

    if not isinstance(key, (bytes, bytearray)):
        raise TypeError("key: expected bytes or bytearray, but got %r" % type(key).__name__)

@Niek-Okido
Copy link

Niek-Okido commented Dec 12, 2019

thanks helpfull man made my day !!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment