Skip to content

Instantly share code, notes, and snippets.

Created April 18, 2012 09:14
What would you like to do?
Simple python XOR encrypt/decrypt
# NB : this is not secure
# from
# added base64 encoding for simple querystring :)
def xor_crypt_string(data, key='awesomepassword', encode=False, decode=False):
from itertools import izip, cycle
import base64
if decode:
data = base64.decodestring(data)
xored = ''.join(chr(ord(x) ^ ord(y)) for (x,y) in izip(data, cycle(key)))
if encode:
return base64.encodestring(xored).strip()
return xored
secret_data = "239054"
print xor_crypt_string(secret_data, encode=True)
print xor_crypt_string(xor_crypt_string(secret_data, encode=True), decode=True)
Copy link

poltronSuperstar commented Mar 22, 2019

# NB : this is not secure

That's not entirely accurate, if key is cycled several times it's indeed trivial to break with frequency analysis. But with a key as long as what you want en encrypt, it doesn't get more secure that that. Therefore it may be a perfect fit for particular use cases (mine: I have to encrypt third party API keys, fixed length, one cipher key generated per API key.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment