The bit-wise XOR operation applied twice with the same key (a series of bits) returns back the original input. If this key is kept secret, generated randomly then we basically have a one-time pad with which we can encrypt messages. This is the best possible encryption in theory (except maybe quantum encryption). An example with NumPy is given below:
1 2 3 4 5 6 7 8 9 10 11 12
import numpy as np a = map(ord, "This is a very secret message!!! Don't tell anybody about it!!!") key = np.random.random_integers(0, 127, len(a)) #encrypt x = np.bitwise_xor(a, key) print "Encrypted", ''.join(map(chr, x)) #decrypt decrypted = np.bitwise_xor(x, key) print "Decrypted", ''.join(map(chr, decrypted))
- Line 3 creates an integer array from the ASCII integer values of the characters in the message.
- Line 4 creates the random key. The key has the same length as the message string.
- Line 7 encrypts the message with the NumPy bit-wise XOR function.
- Line 11 decrypts the message back with the NumPy bit-wise XOR function.
The message is encrypted and decrypted as follows:
1 2 3
Encrypted 9AI<"9K.M =/ ^bR,n>)/WL\c\ HR](>py'^~9\LV8VNW:l Decrypted This is a very secret message!!! Don't tell anybody about it!!!
In principle this encryption should be safe. However, you have to make certain that nobody can find out what the key is. And the key should be sufficiently random. We can certainly do some statistical tests to find out whether the key is random enough. I will put that in the Backlog for now.