Skip to content
Rahul Sridhar edited this page Oct 27, 2017 · 1 revision

Collection of useful python functions for CTFs

chr and ord (ASCII to integers)

assert(chr(0x41) == 'A')
assert(ord('A') == 0x41)

binascii (hex-strings to bytes)

import binascii
x = binascii.unhexlify('4142434445')
assert(x == 'ABCDE')
y = binascii.hexlify(x)
assert(y == '4142434445')

base64 (base64 encoding/decoding)

import base64
y = base64.b64encode('asdfasdf')
assert(y == 'YXNkZmFzZGY=')
x = base64.b64decode('YXNkZmFzZGY=')
assert(x == 'asdfasdf')

struct (to/from byte strings to ints)

import struct
x = struct.pack('<I', 0x44434241)
assert(x == 'ABCD')
y = struct.unpack('<I', y)
assert(y == (0x44434241,))

The <I stands for "little-endian 32-bit integer". Note that unpack returns a tuple. N.B.: If you're using pwntools just use p32 and u32 instead!