Python: binascii.a2b_hex gives the string "Odd length"

I have a hexadecimal value that I extract from a text file, then I pass it to a2b_hex to convert it to the corresponding binary representation. Here is what I have:

k = open('./' + basefile + '.key', 'r')
k1 = k.read()
k.close()
my_key = binascii.a2b_hex(k1)

When I type k1, this is as expected: 81e3d6df

Here is the error message:

Traceback (most recent call last):
  File "xor.py", line 26, in <module>
    my_key = binascii.a2b_hex(k1)
TypeError: Odd-length string

Any suggestions? Thank!

+5
source share
4 answers

Are you sure that the file is not superfluous? Spaces for example?

Try k1.strip()

+7
source

I suspect there is a newline ending line at the end of the file. Separate the string before passing it to binascii.

Please note that now there are more than a simple writing: k1.strip().decode('hex').

+4
source

read() . '\n', k1.

binascii.a2b_hex(k1.strip()) , , binascii.a2b_hex(k1[:8]).

+3
source

I'm more interested in what happens if you run the following code:

with open("./" + basefile + ".key") as key_file:
   key = key_file.read()
   print len(key), key

Learning to talk? There are probably some additional characters that you simply don’t see when printing. In these cases, be sure to print the length of the string.

+2
source

All Articles