5

This line works perfectly in python 2.7.6, but fails in Python 3.3.5. How i can decode to hex value in Python 3.

return x.replace(' ', '').replace('\n', '').decode('hex')

Traceback

AttributeError: 'str' object has no attribute 'decode'
ajknzhol
  • 6,322
  • 13
  • 45
  • 72
  • Maybe duplicated: see this [post](http://stackoverflow.com/questions/2340319/python-3-1-1-string-to-hex) – Salvatore Avanzo Apr 12 '14 at 17:30
  • 3
    The [Heartbleed Python script](https://gist.github.com/takeshixx/10107280) is written for Python 2, not Python 3 :-) You'll need to address more issues other than the payload definition. – Martijn Pieters Apr 12 '14 at 17:40
  • @MartijnPieters I sense that we are going to be getting many similar quetsions very soon... – anon582847382 Apr 12 '14 at 17:45
  • 1
    @rcomp Note that the script has been ported to Python 3 by the github community: https://gist.github.com/dyatlov/10192468 – anon582847382 Apr 12 '14 at 17:48

1 Answers1

2

To convert hexadecimal to a string, use binascii.unhexlify.

>>> from binascii import unhexlify
>>> unhexlify(x.replace(' ', '').replace('\n', ''))

However, you first need to make x into bytes to make this work, for Python 3. Do this by doing:

>>> x = x.encode('ascii', 'strict')

And then do the hex-to-string conversion.

anon582847382
  • 19,907
  • 5
  • 54
  • 57
  • Looking at the [original source](https://gist.github.com/takeshixx/10107280) the point is to produce *bytes* to send over a socket. The decode isn't needed in that case. – Martijn Pieters Apr 12 '14 at 17:41
  • NP, I was just [answering a different question about the same script](http://stackoverflow.com/questions/23033219/heartbleed-python-test-script/23033261#23033261) and recognized the line. – Martijn Pieters Apr 12 '14 at 17:43
  • note: `x.encode('ascii', 'strict')` is not necessary on Python before/after 3.2 – jfs Apr 12 '14 at 17:58
  • @J.F.Sebastian I don't quite understand you, but would what I have done in my edit be preferrable? – anon582847382 Apr 12 '14 at 18:04
  • `unhexlify()` doesn't work with `str` objects in Python 3.2. Assuming that `x` contains hexdigits then you could use `x.encode('ascii', 'strict')` to convert `str` object to `bytes`. – jfs Apr 12 '14 at 20:12