0

I have a bytes key define as:

KEY = b'\xb5\x89\xd5\x03\x03\x96`\x9dq\xa7\x81\xed\xb2gYR'

I want this to be formatted like shellcode, i.e two hexa characters like: \x41\x42\x43...

So I tried to do it like this:

KEY = b'\xb5\x89\xd5\x03\x03\x96`\x9dq\xa7\x81\xed\xb2gYR'
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?

1 Answer 1

3

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

KEY = b'\xb5\x89\xd5\x03\x03\x96`\x9dq\xa7\x81\xed\xb2gYR'
print(''.join(f'\\x{b:02x}' for b in KEY))

Output:

\xb5\x89\xd5\x03\x03\x96\x60\x9d\x71\xa7\x81\xed\xb2\x67\x59\x52
Sign up to request clarification or add additional context in comments.

2 Comments

thank you, would you mind explaining the syntax f'\\x{b:02x}'?
That's called an f-string and the syntax was added in Python 3.6. {b:02x} says "format value b as 2 hex digits with leading zeros". See the Format specification mini-language

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.