One-Time Pad Program in Python Language
One-Time Pad Program in Python Language
Introduction:
A one-time pad (OTP) is a symmetric encryption algorithm that cannot be cracked. It requires
the use of a single-use pre-shared key that is larger than or equal to the size of the message being
sent.
To encrypt a message with an OTP, the sender and receiver must both have a copy of the key.
The sender then XORs ("exclusive or") the key with the message to produce the ciphertext. The
receiver decrypts the message by XORing the ciphertext with the key.
The OTP is perfectly secure, meaning that it is impossible for an attacker to decrypt the
ciphertext without knowing the key. This is because the key is completely random and is used
only once.
OTPs are often used in espionage and other high-security applications where absolute secrecy is
required. However, they are not practical for everyday use because they require the sender and
receiver to have a pre-shared key that is as long as the message being sent.
Algorithm:
The algorithm for the one-time pad cipher, as implemented in the Python code, is as follows:
1. Generate a random key of the same length as the message being encrypted.
2. XOR the key with the message to produce the ciphertext.
3. To decrypt the ciphertext, XOR the ciphertext with the key.
The following is a more detailed explanation of each step:
Step 1: Generate a random key.
The key is the most important part of the one-time pad cipher, so it is important to generate a
truly random key. The Python code uses the random module to generate a random string of
characters. The length of the key should be at least as long as the message being encrypted.
Step 2: XOR the key with the message.
XOR (exclusive or) is a binary operation that returns 1 if either of its inputs is 1 and 0 otherwise.
It is used to encrypt the message by XORing it with the key.
Implementation of one-time pad cipher:
import random
# Function to generate key
def generate_key(length):
key = ""
for i in range(length):
key +=
random.choice("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345
6789")
return key
# Function to encrypt key
def encrypt(message, key):
ciphertext = ""
for i in range(len(message)):
ciphertext += chr(ord(message[i]) ^ ord(key[i]))
return ciphertext
# Function to decrypt key
def decrypt(ciphertext, key):
message = ""
for i in range(len(ciphertext)):
message += chr(ord(ciphertext[i]) ^ ord(key[i]))
return message
# Function for calling the main program.
def main():
message = input("Enter the message to encrypt: ")
key = generate_key(len(message))
ciphertext = encrypt(message, key)