1

Trying to encrypt to HMAC-SHA256 by giving my script a key and message.

A popular example that I saw online fails to run on my machine:

import hmac
import hashlib
import binascii

def create_sha256_signature(key, message):
    byte_key = binascii.unhexlify(key)
    message = message.encode()
    enc = hmac.new(byte_key, message, hashlib.sha256).hexdigest().upper()
    print (enc)

create_sha256_signature("KeepMySecret", "aaaaa")

why am I getting this error?

Traceback (most recent call last):
  File "encryption.py", line 12, in <module>
    create_sha256_signature("SaveMyScret", "aaaaa")
  File "encryption.py", line 8, in create_sha256_signature
    byte_key = binascii.unhexlify(key)
binascii.Error: Odd-length string

How should I change my code so I will be able to give my own short key?

1 Answer 1

3

When you call unhexlify it implies that your key is a hexadecimal representation of bytes. E.g. A73FB0FF.... In this kind of encoding, every character represents just 4 bits and therefore you need two characters for a byte and an even number of characters for the whole input string.

From the docs:

hexstr must contain an even number of hexadecimal digits

But actually the given secrets "SaveMySecret" or "KeepMySecret have not only a odd number of characters, but are not even valid hex code, so it would fail anyway with:

binascii.Error: Non-hexadecimal digit found

You can either provide a key in hex encoded form, or instead of calling unhexlify use something like

byte_key = key.encode('utf-8')

to get bytes as input for hmac.new()

Sign up to request clarification or add additional context in comments.

3 Comments

This works but now the output is all uppercase. I expected it to be lowercase as typically.. Didn't want to use lower() function.
The .upper() makes it uppercase, so just remove that.
Didn't put attention to the upper(). Thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.