Adventures in Cryptography with Python – XOR Cipher

XOR cipher is a simple additive encryption technique in itself but is used commonly in other encryption techniques. The truth table for XOR cipher is as below. If the bits are same then the result is 0 and if the bits are different then the result is 1.

 

Bit 1 Operation Bit 2 Result
0 0 0
1 0 1
0 0 1
1 1 0

 

Let’s take an example. We would encrypt Sun using the key 01010010 repeatedly .

Encryption
Text          |     S    |     u     |     n       |
ACII Code     |    083   |    117    |    110      |
Binary        | 01010011 |  01110101 |  01101110   |
Key           | 01010010 |  01010010 |  01010010   |
Cipher        | 00000001 |  00100111 |  00111100   |

Now if we XOR the cipher with the same key we will get back the out original text.

Decryption
Cipher        | 00000001 |  00100111 |  00111100   |  
Key           | 01010010 |  01010010 |  01010010   |
Output        | 01010011 |  01110101 |  01101110   |
ACII Code     |    083   |    117    |     110     |
Text          |     S    |     u     |      n      |

This encryption we just did was not very secure because used the same key over and over again. To make our encryption more secure we should use a unique key and not the one which is repetitive in nature. A good technique that could be used is One-time Pad. This makes the encryption much more secure to the brute force attack.

XOR encryption and decryption

The encryption and decryption using XOR has the same code. A python implementation for the same is below:

 

input_str = raw_input("Enter the cipher text or plain text: ")
key = raw_input("Enter the key for encryption or decryption: ")
no_of_itr = len(input_str)
output_str = ""


for i in range(no_of_itr):
    current = input_str[i]
    current_key = key[i%len(key)]
    output_str += chr(ord(current) ^ ord(current_key))

print "Here's the output: ", output_str

And here’s a sample run

Image showing sample run of ROT13 encoder decoder

Image showing sample run of XOR encryption and decryption

 

The entire source code for this post can be found at https://github.com/abhishuk85/cryptography-plays

Any questions, comments or feedback are most welcome.