Skip to content

Instantly share code, notes, and snippets.

@jtoll
Last active September 2, 2019 23:33
Show Gist options
  • Save jtoll/8440141 to your computer and use it in GitHub Desktop.
Save jtoll/8440141 to your computer and use it in GitHub Desktop.
Simple functions for converting between string, hex, and int for a crypto course using Python
def str2hex (x):
return x.encode('hex')
def hex2str (x):
return x.decode('hex')
def str2int (x):
return map(ord, x)
def int2str (x):
return "".join(map(chr, x))
def hex2int (x):
return map(lambda y: int(y, 16), [x[i:i+2] for i in range(0,len(x), 2)])
def int2hex (x):
return "".join(map(chr, x)).encode('hex')
def splitHex(x):
return [x[i:i+2] for i in range(0,len(x), 2)]
def hexxor (x, y):
# XOR two hexadecimal strings, returning a hexadecimal string
# warning: zip will truncate length to the shorter of x or y
return int2hex([a ^ b for (a, b) in zip(hex2int(x), hex2int(y))])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment