Just Cryptography

Learn Cryptography and Information Security

Home » Blog » Vernam cipher in Python

# Vernam cipher in Python

Vernam cipher was introduced by Gilbert Vernam in 1918. In this post, I’ll explain the algorithm and show the implementation in Python.

Vernam cipher is the ultimate defense against the cryptanalysis used to break the Vigenère cipher.

The mentioned attack relies on the fact that the key and the plain text share the same frequency distribution of letters.

In the case of the Vernam cipher, we create a key that is the same size as the plain text and has no statistical relation to it.

Once we have the key, the Python implementation of the Vernam cipher is quite easy. We just need to perform an XOR between each bit of the plain text and the corresponding bit of the key.

Notice that the operation XOR works on bits and not in characters.

Internally, Python handles XOR between integers, so we don’t need to convert the integer value (decimal) to binary code, apply the XOR, and convert it back from binary to decimal.

## The Vernam cipher

The algorithm is as follows:

ci = pi ki , where pi is the ith binary digit of the plain text, ki is the ith binary digit of the key, ci is the ith binary digit of the cipher text and ⊕ is the XOR operation.

See the Python code for the Vernam cipher below.

``````def Vernam (text, key):
cipher_text = ''
for i in range(len(text)):
character = chr(ord(text[i]) ^ ord(key[i]))
cipher_text = cipher_text + character
return cipher_text
``````

The function ord in Python returns the Unicode value of (an integer representation) of a character. The function chr returns the character corresponding to the Unicode value.

The operator ^ in Python is the XOR operator.

So, we do an XOR bit by bit between the plain text and the key. After concatenating all the results, we can return the cipher text.

Because of the properties of the XOR, the decryption process is just the same. In other words, we can encrypt and decrypt using the same procedure. The only difference is the input text.

## Example of Python console application

So, let’s use the functions above in a Python console application so we can see the results.

``````if __name__=="__main__":
text = "My Secret text"
key = 'mjcipuqszsymzp'
print ("The key is: ", key)
cipher_text = Vernam(text, key)
print("The cipher text is: ", repr(cipher_text))

plain_text = Vernam(cipher_text, key)
print("The original text is: ", plain_text)
``````

If we execute the code above, we get the following result:

H@ppy coding!