Converting between bytes and hex

I was working on set 1 in the matasano crypto challenges and coding along using python2 and later found out from here that python2 is legacy and I should start using python3.

I had the code for converting hex string working in python2 but was having trouble doing it in python3 due to some of the quark between bytes and string. Here are the summary of what I found.

# create a string
>>> s='hello'
>>> s
'hello'

# string to byte encoding in ascii
>>> bs=bytes(s, encoding='utf-8')
>>> bs
b'hello'

# byte encoding in ascii to string
>>> bs.decode()
'hello'

# byte encoding in ascii to hex representation in byte encoding in ascii
>>> hb=binascii.hexlify(bs)
b'68656c6c6f'

# hex representation in byte encoding in ascii to byte encoding in ascii
>>> binascii.unhexlify(hb)
b'hello'

# hex representation in byte encoding in ascii to hex representation string
>>> hs = hb.decode()
>>> hs
'68656c6c6f'

# hex representation string to byte encoding in ascii
>>> binascii.unhexlify(hs)
b'hello'

# string to hex representation in byte encoding in ascii : attempt in error 
>>> binascii.hexlify(s)
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
TypeError: 'str' does not support the buffer interface

Notice that both hex representation in byte encoding of ascii (hb) and hex representation string (hs) can use unhexlify and get the byte encoding in ascii of ‘hello’. However, we can only hexlify the byte encoding in ascii of ‘hello’ and not the string ‘hello’ itself. To get a string convert to a hex representation of byte encoding in ascii, we need to do it in 2 steps.

>>> binascii.hexlify(bytes(s, encoding='ascii'))
b'68656c6c6f'
Advertisements