0

I need to convert a string such as 5555555547aa into a string of characters (that one would be �GUUUU). I have a function working in python2 which is posted below, but I can't get anything to work right in python3. How would I do this?

    def hex_conv(hex_str):
      arr = [hex_str[i:i+2] for i in range(0, len(hex_str), 2)]
      rev = arr[::-1]
      out_str = ""
      for i in rev:
        print(i)
        out_str += ("\\x" + i).decode("string_escape")
      return out_str

More Clearly of what I need outputted (in Python2):

print('\xaa\x47\x55\x55\x55\x55')

I have tried

print(bytes.fromhex("5555555547aa")[::-1].decode("utf-8", errors="replace"))

which doesn't quite work. It appears to produce the same output but the actual bytes are different.

Note: The output of this is going to be piped into another program (for binary exploitation) so the bytes need to be printed exact.

jakebacker44
  • 35
  • 1
  • 7
  • Does this answer your question? [hexadecimal string to byte array in python](https://stackoverflow.com/questions/5649407/hexadecimal-string-to-byte-array-in-python) – SuperStormer Mar 27 '21 at 19:44
  • Not quite. That just converts it to a byte array which still has \xaa as itself as opposed to �. – jakebacker44 Mar 27 '21 at 20:14
  • then do `.decode("utf8", errors="replace")` if you want a regular str with the error chars. – SuperStormer Mar 27 '21 at 20:16
  • That's seems really close but it's quite correct. That seems to produce the hex 0x5555555547bdbfef when I need 0x5555555547aa – jakebacker44 Mar 27 '21 at 20:25
  • Wait, binexp? Just keep it as a bytestring, you can send bytestrings to subprocess or pwntools or whatever you're using. – SuperStormer Mar 27 '21 at 20:30
  • Or if you're outputting to stdout, use [sys.stdout.buffer.write](https://stackoverflow.com/questions/31917595/how-to-write-a-raw-hex-byte-to-stdout-in-python-3) instead – SuperStormer Mar 27 '21 at 20:32
  • The second one worked! Feel free to make an actual answer and I'll go accept it. I'm planning on learning pwntools soon but sys.stdout.buffer.write will suffice for now. Thanks! – jakebacker44 Mar 27 '21 at 20:37

1 Answers1

1

You just need to combine 2 steps: convert from hex to a bytestring with bytes.fromhex, and to print a bytestring to stdout using sys.stdout.buffer.write. Putting it all together:

import sys
sys.stdout.buffer.write(bytes.fromhex("5555555547aa")[::-1])

Sourced from hexadecimal string to byte array in python and How to write a raw hex byte to stdout in Python 3?

SuperStormer
  • 4,997
  • 5
  • 25
  • 35