XOR encryption is a great solution to go with when a task requires that a piece of data is encrypted with a key when one doesn’t have the means to use a more well-rounded algorithm. I’ve used it on a few occasions with great success. In this document, we’ll discuss how to code the XOR cipher in Python and we’ll cover the pros and cons of using it.
from itertools import izip, cycle def xor_crypt_string(data, key): return ''.join(chr(ord(x) ^ ord(y)) for (x,y) in izip(data, cycle(key)))
The code for XOR string encryption is surprisingly simple since the whole concept of XOR encryption is simple. Basically, it iterates over a piece of data, and for every letter, it XORs it with the key. In this function, it is done in a list comprehension. Once the list is built, it gets joined into a string and returned. Encryption and decryption both use the same function.
my_data = "Hello. This is a secret message! How fun." my_key= "firefly" # Do the actual encryption encrypted = xor_crypt_string(my_data, key=my_key) # This will obtain the original data from the encrypted original = xor_crypt_string(encrypted, key=my_key)
XOR encryption is a very quick way to encrypt/decrypt strings based on a key. They’re perfect for cases where you’d like to transfer data safely (but not too safely. Read the next section). Furthermore, the XOR cipher needs only one function that does both encrypting and decrypting. For instance, in the above code if you encrypt something and then feed it directly back into the function with the same key, it’ll produce the unencrypted data. Also, the XOR cipher is considered the only perfect encryption method under the proper scheme for a one-time pad. (There are exceptions. Keep reading…)
Okay, remember when I said that it can be a perfect encryption? Well, that comes with a few limitations. Namely, the key must be completely random, the key must be the length of the data being encrypted, and the key can be used once and only once. If those rules aren’t followed, then the cipher can be broken using frequency analysis.
The Right Way
Use the Python Cryptography Toolkit. It provides you with plenty of other methods to use instead of XOR encryption. A manual can be found here. Of course, doing it this way causes your code to become less portable since anybody you send it to will also be required to have the toolkit installed.