There are a quite few ways to deal with hexes in python itself.
Convert hex to ascii character
Typing a hexadecimal in the format 0x will show the decimal form of the number. Put chr() on the hexadecimal convert the resultant integer to it’s
>>> 0x4a
74
>>> chr(0x4a)
‘J’
ord
is the opposite of chr
converting ascii into integer in decimal base, while hex
turns integers to hex.
>>> ord(‘G’)
71>>> hex(ord(‘G’))
'0x47'
bytes.fromhex(hex)
converts hex in strings to ascii in bytes format. You can remove the bytes by using .decode()
Meanwhile .encode()
encodes data in bytes.
[ Note: here don’t append \x or 0x to the hex in the string. As you can see, I have just used ‘47’ not ‘0x47’ or ‘\x47’ ]
>>> bytes.fromhex(‘47’)
b’G’
>>> bytes.fromhex(‘47’).decode()
’G’>>> ‘Hello world’.encode()
b’Hello world’
Type in hex in \x format within strings, it will convert the string to the corresponding ascii alphabet on it’s own (if it’s possible, or it will remain in hex form).
>>> ‘\x4a’
‘J’
Also, we could use long_to_bytes
for this purpose too from Crypto
module too. Here, however you get back data in bytes and not in string. bytes_to_long
does just the opposite. It converts bytes to integer in decimal base.
>>> from Crypto.Util.number import long_to_bytes, bytes_to_long
>>> long_to_bytes(0x4a) #here 0x4a automatically translates to 74
b‘J’
>>> bytes_to_long(b’h4kr c4t’) #Converts ascii characters to their
# decimal bases7508744616647275636
>>> hex(bytes_to_long(b’h4kr c4t’)) #converts to hex format
‘0x68346b7220633474’
We can do the same with unhexlify
from binascii
module too.
hexlify converts ascii characters directly to their hexes (not their 10 bases)
>>> from binascii import unhexlify
>>> unhexlify(b‘4a’)
b‘J’>>> hexlify(b‘h’)
b‘68’
How to same with bash?
Use: echo ‘encode this’ | base64
For decoding, echo ‘ZGVjb2RlIHVzaW5nIGJhc2gK’ | base64 -d
Convert decimal to binary
Use bin()
to convert decimal to binary numbers
>>> bin(15)
‘0b1111’
Ignore the first characters 0b
Converting to base 10 to oct
Use oct()
to convert decimal numbers to their octal form.
>>> oct(10)
‘0o12’
Ignore the first two characters 0o
Converting to base64 and decoding them in python
base64 is probably the most commonly used encoding, we know from the base64
encoding we can import b64encode
& b64decode
Since b64encode accepts bytes format only we need to encode data with .encode()
out put is in bytes so decode with .decode()
>>> from base64 import b64encode, b64decode
>>> b64encode(‘hello world’.encode()).decode()
‘aGVsbG8gd29ybGQ=’
>>> b64decode(‘aGVsbG8gd29ybGQ=’).decode()
’hello world’
Rm9sbG93IG1lIGhlcmUgYW5kIGNsYXAgZm9yIHRoaXMgYXJ0aWNsZSwgaXQgZW5jb3VyYWdlcyBtZSB3cml0ZSBtb3JlIGFydGljbGVzLiBIYXZlIGEgbmljZSBkYXkgOikK