jrz
jrz

Reputation: 1387

Python script to encrypt a message fails

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?

Upvotes: 1

Views: 174

Answers (1)

jps
jps

Reputation: 22515

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()

Upvotes: 3

Related Questions