9

I have a hex value that I'm grabbing from a text file, then I'm passing it to a2b_hex to convert it to the proper 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 print k1, it 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? Thanks!

Magicked
  • 637
  • 3
  • 11
  • 20
  • Thanks everyone. I had tried to strip the input earlier, but I didn't do k1 = strip(k1). I did strip(k1). – Magicked Sep 16 '10 at 22:25

4 Answers4

8

Are you sure the file doesn't have something extra in it? Whitespace, for instance?

Try k1.strip()

Matti Virkkunen
  • 63,558
  • 9
  • 127
  • 159
6

I suspect there is a trailing newline at the end of the file. Strip the string before passing it to binascii.

Note there's now also a simpler spelling: k1.strip().decode('hex').

bobince
  • 528,062
  • 107
  • 651
  • 834
  • 1
    Sometimes when calling `text.strip().decode('hex')` it raises `TypeError: Odd-length string` too :( – 0x90 Jan 07 '14 at 22:06
3

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

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

Care to tell? There is probably some extra character you just don't see when printing. In these cases, make sure to print the length of the string.

Jim Brissom
  • 31,821
  • 4
  • 39
  • 33
3

read() doesn't strip newlines. If there's a '\n' at the end of your file, it'll be in k1.

Try binascii.a2b_hex(k1.strip()) or possibly binascii.a2b_hex(k1[:8]).

Seth
  • 45,033
  • 10
  • 85
  • 120