Home » Blog » One-Time Pad cipher in Python

One-Time Pad cipher in Python


The One-Time Pad cipher was proposed by Joseph Mauborgne. In this post, I’ll show you a Python implementation of this cipher.

This cipher is the same as the Vernam cipher. The only difference is that every key is used only once. So, we need to generate a random key every time we encrypt a new message.

In theory, this scheme offers complete security, however, it has two practical flaws:

“1. There is the practical problem of making large quantities of random keys. Any heavily used system might require millions of random characters on a regular basis. Supplying truly random characters in this volume is a significant task. 2. Even more daunting is the problem of key distribution and protection. For every message to be sent, a key of equal length is needed by both sender and receiver. Thus, a mammoth key distribution problem exists.” Source: Cryptography and Network Security by Stallings.

Because of the above, it is used in practice mainly in low-bandwidth channels requiring very high security.

To show how this can be achieved in Python, we just need to use the code for the Vernam cipher, and every time we want to encrypt a new message, we generate a new key.

As an example, let’s create a Python console menu application, and give the possibility to encrypt/decrypt using the menu.

See the code below:

menu_options = {
    1: 'Encrypt and decrypt',
    2: 'Exit',
}

def print_menu():
    for key in menu_options.keys():
        print (key, '--', menu_options[key] )

def option1():
     plain_text = input("Enter the plain text: ")
     key = generate_key(len(plain_text))
     print ('key: ', key)
     cipher_text = Vernam(plain_text,key)
     print('cipher text: ', repr(cipher_text))
     text = Vernam(cipher_text,key)
     print('plain text, ', text)
 

if __name__=='__main__':
    while(True):
        print_menu()
        option = ''
        try:
            option = int(input('Enter your choice: '))
        except:
            print('Wrong input. Please enter a number ...')
        #Check what choice was entered and act accordingly
        if option == 1:
           option1()
        elif option == 2:
            print('Thanks message before exiting')
            exit()
        else:
            print('Invalid option.')

Remember we are using the same function implemented in the Vernam cipher post.

All that is left now is to implement the function to generate random keys.

import random

def generate_key(size):
    key = ''
    for _ in range(size):
        key = key + random.choice('abcdefghijklmnopqrstuvwxyz')
    return key

See below a sample of the execution of the Python code.

output example of the one-time pad cipher in python

As you can see, every time we want to encrypt a new text, a new random key is generated.