mgjk mgjk - 2 months ago 23
Python Question

How to cast binary into a string in python

For infosec projects I'm using strings as a kind of byte array. This is commonly done in vulnerability testing. In building the byte array, I want to concatenate printable characters and nonprintable characters.

This is not a question of conversion, I really want to cast the type. I could write a function or method around chr(), but there must be a better way.

>>> print "A"*10 + chr(0x20) + "B"*10
AAAAAAAAAA BBBBBBBBBB


E.g., what if I have a large binary array to insert?

>>> print "A"*10 + 0xBEEF + "B"*10
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects

>>> print "A"*10 + 0xBEEFBEEFBEEFBEEFBEEFBEEF + "B"*10
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'long' objects


I may be using the wrong data types here because I'm pretty sure that I'm not even guaranteed that strings have 8-bit bytes.




An example of what I would hope for:

>>> print "A"*10 + 0xBEEFBEEFBEEFBEEFBEEFBEEF + "B"*10
AAAAAAAAAA������������BBBBBBBBBB

Answer Source

You can use binascii.unhexlify if it's a bit of a chore to type out the escaped hexadecimals in a string, eg:

from binascii import unhexlify

b = 'A'*10 + unhexlify('BEEF' * 6) + 'B'*10
# 'AAAAAAAAAA\xbe\xef\xbe\xef\xbe\xef\xbe\xef\xbe\xef\xbe\xefBBBBBBBBBB'

In Python 3 though, you'd have to make sure you start with byte strings (or you'll receive a TypeError: Can't convert 'bytes' object to str implicitly):

b'A'*10 + unhexlify('BEEF' * 6) + b'B'*10
# b'AAAAAAAAAA\xbe\xef\xbe\xef\xbe\xef\xbe\xef\xbe\xef\xbe\xefBBBBBBBBBB'