How to convert a hexstring to shellcode format?

Question:

I have a bytes key define as:

KEY = b’xb5x89xd5x03x03x96`x9dqxa7x81xedxb2gYR’

I want this to be formatted like shellcode, i.e two hexa characters like: x41x42x43…

So I tried to do it like this:

KEY = b'xb5x89xd5x03x03x96`x9dqxa7x81xedxb2gYR'
hexkey = KEY.hex()
l = []

for i in range(0, len(hexkey) - 2, 2):
    b = '\x' + hexkey[i] + hexkey[i+1]
    l.append(b)

but this isn’t escaping the backslash for some reason, I get this output:

[‘\xb5’, ‘\x89’, ‘\xd5’, ‘\x03’, ‘\x03’, ‘\x96’, ‘\x60’,
‘\x9d’, ‘\x71’, ‘\xa7’, ‘\x81’, ‘\xed’, ‘\xb2’, ‘\x67’,
‘\x59’]

what am i doing wrong? Is there a better way to do this?

Asked By: Slava

||

Answers:

.join() and print them. You can iterate over the bytes directly as well:

KEY = b'xb5x89xd5x03x03x96`x9dqxa7x81xedxb2gYR'
print(''.join(f'\x{b:02x}' for b in KEY))

Output:

xb5x89xd5x03x03x96x60x9dx71xa7x81xedxb2x67x59x52
Answered By: Mark Tolonen
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.