I am a Python newbie :) and trying to get less n00b :)
Hexadecimal, binary (etc) conversion
That's what I call:- 'axelle' : a string
- [10, 20, 30] : a (byte) array
- '\xde\xad\xbe\xef' : a hexadecimal byte string
- 'de ad be ef' : that's a hexadecimal byte string too. Just formatted a bit differently
- '6178656c6c65' : that's a hexadecimal string.
String to byte array
'axelle' -> [97, 120, 101, 108, 108, 101] In [1]: string = 'axelle' In [5]: list(bytearray(string)) or In [6]: map(ord,string)
Hexadecimal byte string to byte array
'\xde\xad\xbe\xef' -> [0xDE, 0xAD, 0xBE, 0xEF] map(ord, '\xde\xad\xbe\xef') or list(bytearray(b'\xde\xad\xbe\xef'))Same, but the hexadecimal string has a space separator:
"de ad be ef" -> [0xDE, 0xAD, 0xBE, 0xEF] list(bytearray.fromhex("de ad be ef"))
String to hexadecimal string (or reciprocally)
'axelle' -> '6178656c6c65' string.encode("hex")Reciprocally, it is:
hexstring.decode('hex')
Writing a byte array to a file
f = open('test', 'wb+') f.write(bytearray(ba)) f.close()
Base64
To do base64 with a different alphabet:import string crypt_alphabet="./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" std_alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" s = s.translate(string.maketrans(crypt_alphabet, std_alphabet) base64.b64decode(new_s)
XOR
from itertools import izip, cycle import string def xor(message, key): return ''.join(chr(ord(x) ^ ord(y)) for (x,y) in izip(message, cycle(key))) key = 'THEKEY' xor(buffer, key)
Add system logs
syslog.syslog.openlog(logoption=syslog.LOG_PID, facility=syslog.LOG_USER) syslog.syslog(syslog.LOG_WARNING, "keyboard interrupt")
Time
import time time.gmtime(123456)From epoch to localtime:
time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(1428316200))From local time to epoch:
print time.mktime(time.strptime("10.08.2015 00:00:00", "%d.%m.%Y %H:%M:%S"))
More
To display a long variable page by page in the interactive python shell, add % in front%page l
Filter
To filter out a long string and show only those matching a given string:l = d.get_strings() filter(lambda x:'http' in x, l)
Markdown
This is an easy way to convert markdown syntax to HTML using Python:sudo pip install markdown python -m markdown blah.md > blah.html