Implementation of Vernam Cipher or One Time Pad Algorithm
Last Updated :
23 Jul, 2025
One Time Pad algorithm is the improvement of the Vernam Cipher, proposed by An Army Signal Corp officer, Joseph Mauborgne. It is the only available algorithm that is unbreakable(completely secure). It is a method of encrypting alphabetic plain text. It is one of the Substitution techniques which converts plain text into ciphertext. In this mechanism, we assign a number to each character of the Plain-Text.
The two requirements for the One-Time pad are
- The key should be randomly generated as long as the size of the message.
- The key is to be used to encrypt and decrypt a single message, and then it is discarded.
So encrypting every new message requires a new key of the same length as the new message in one-time pad.
The ciphertext generated by the One-Time pad is random, so it does not have any statistical relation with the plain text.
The assignment is as follows:
A | B | C | D | E | F | G | H | I | J |
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
K | L | M | N | O | P | Q | R | S | T |
10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 |
U | V | W | X | Y | Z |
20 | 21 | 22 | 23 | 24 | 25 |
The relation between the key and plain text: In this algorithm, the length of the key should be equal to that of plain text.
Examples:
Input: Message = HELLO, Key = MONEY Output: Cipher - TSYPM, Message - HELLO Explanation: Part 1: Plain text to Ciphertext Plain text — H E L L O ? 7 4 11 11 14 Key — M O N E Y ? 12 14 13 4 24 Plain text + key ? 19 18 24 15 38 ? 19 18 24 15 12 (= 38 – 26) Cipher Text ? T S Y P M Part 2: Ciphertext to Message Cipher Text — T S Y P M ? 19 18 24 15 12 Key — M O N E Y? 12 14 13 4 24 Cipher text - key ? 7 4 11 11 -12 ? 7 4 11 11 14 Message ? H E L L O Input: Message = SAVE, Key = LIFE Output: Cipher - DIAI Message - SAVE
Security of One-Time Pad
- If any way cryptanalyst finds these two keys using which two plaintext are produced but if the key was produced randomly, then the cryptanalyst cannot find which key is more likely than the other. In fact, for any plaintext as the size of ciphertext, a key exists that produces that plaintext.
- So if a cryptanalyst tries the brute force attack(try using all possible keys), he would end up with many legitimate plaintexts, with no way of knowing which plaintext is legitimate. Therefore, the code is unbreakable.
- The security of the one-time pad entirely depends on the randomness of the key. If the characters of the key are truly random, then the characters of the ciphertext will be truly random. Thus, there are no patterns or regularities that a cryptanalyst can use to attack the ciphertext.
Advantages
- One-Time Pad is the only algorithm that is truly unbreakable and can be used for low-bandwidth channels requiring very high security(ex. for military uses).
Disadvantages
- 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.
- 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.
Below is the implementation of the Vernam Cipher:
C++
// C++ program Implementing One Time Pad Algorithm
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
// Method 1
// Returning encrypted text
string stringEncryption(string text, string key)
{
// Initializing cipherText
string cipherText = "";
// Initialize cipher array of key length
// which stores the sum of corresponding no.'s
// of plainText and key.
int cipher[key.length()];
for (int i = 0; i < key.length(); i++) {
cipher[i] = text.at(i) - 'A' + key.at(i) - 'A';
}
// If the sum is greater than 25
// subtract 26 from it
// and store that resulting value
for (int i = 0; i < key.length(); i++) {
if (cipher[i] > 25) {
cipher[i] = cipher[i] - 26;
}
}
// Converting the no.'s into integers
// Convert these integers to corresponding
// characters and add them up to cipherText
for (int i = 0; i < key.length(); i++) {
int x = cipher[i] + 'A';
cipherText += (char)x;
}
// Returning the cipherText
return cipherText;
}
// Method 2
// Returning plain text
static string stringDecryption(string s, string key)
{
// Initializing plain text
string plainText = "";
// Initializing integer array of key length
// which stores difference
// of corresponding no.'s of
// each character of cipherText and key
int plain[key.length()];
// Running for loop for each character
// subtracting and storing in the array
for (int i = 0; i < key.length(); i++) {
plain[i] = s.at(i) - 'A' - (key.at(i) - 'A');
}
// If the difference is less than 0
// add 26 and store it in the array.
for (int i = 0; i < key.length(); i++) {
if (plain[i] < 0) {
plain[i] = plain[i] + 26;
}
}
// Converting int to corresponding char
// add them up to plainText
for (int i = 0; i < key.length(); i++) {
int x = plain[i] + 'A';
plainText += (char)x;
}
// Returning plainText
return plainText;
}
// Method 3
// Main driver method
int main()
{
// Declaring plain text
string plainText = "Hello";
// Declaring key
string key = "MONEY";
// Converting plain text to toUpperCase
// function call to stringEncryption
// with plainText and key as parameters
for (int i = 0; i < plainText.length(); i++) {
// convert plaintext to uppercase
plainText[i] = toupper(plainText[i]);
}
for (int i = 0; i < key.length(); i++) {
// convert key to uppercase
key[i] = toupper(key[i]);
}
string encryptedText = stringEncryption(plainText, key);
// Printing cipher Text
cout << "Cipher Text - " << encryptedText << endl;
// Calling above method to stringDecryption
// with encryptedText and key as parameters
cout << "Message - "
<< stringDecryption(encryptedText, key);
return 0;
}
// This code was contributed by Pranay Arora
Java
// Java program Implementing One Time Pad Algorithm
// Importing required classes
import java.io.*;
// Main class
public class GFG {
// Method 1
// Returning encrypted text
public static String stringEncryption(String text,
String key)
{
// Initializing cipherText
String cipherText = "";
// Initialize cipher array of key length
// which stores the sum of corresponding no.'s
// of plainText and key.
int cipher[] = new int[key.length()];
for (int i = 0; i < key.length(); i++) {
cipher[i] = text.charAt(i) - 'A'
+ key.charAt(i)
- 'A';
}
// If the sum is greater than 25
// subtract 26 from it
// and store that resulting value
for (int i = 0; i < key.length(); i++) {
if (cipher[i] > 25) {
cipher[i] = cipher[i] - 26;
}
}
// Converting the no.'s into integers
// Convert these integers to corresponding
// characters and add them up to cipherText
for (int i = 0; i < key.length(); i++) {
int x = cipher[i] + 'A';
cipherText += (char)x;
}
// Returning the cipherText
return cipherText;
}
// Method 2
// Returning plain text
public static String stringDecryption(String s,
String key)
{
// Initializing plain text
String plainText = "";
// Initializing integer array of key length
// which stores difference
// of corresponding no.'s of
// each character of cipherText and key
int plain[] = new int[key.length()];
// Running for loop for each character
// subtracting and storing in the array
for (int i = 0; i < key.length(); i++) {
plain[i]
= s.charAt(i) - 'A'
- (key.charAt(i) - 'A');
}
// If the difference is less than 0
// add 26 and store it in the array.
for (int i = 0; i < key.length(); i++) {
if (plain[i] < 0) {
plain[i] = plain[i] + 26;
}
}
// Converting int to corresponding char
// add them up to plainText
for (int i = 0; i < key.length(); i++) {
int x = plain[i] + 'A';
plainText += (char)x;
}
// Returning plainText
return plainText;
}
// Method 3
// Main driver method
public static void main(String[] args)
{
// Declaring plain text
String plainText = "Hello";
// Declaring key
String key = "MONEY";
// Converting plain text to toUpperCase
// function call to stringEncryption
// with plainText and key as parameters
String encryptedText = stringEncryption(
plainText.toUpperCase(), key.toUpperCase());
// Printing cipher Text
System.out.println("Cipher Text - "
+ encryptedText);
// Calling above method to stringDecryption
// with encryptedText and key as parameters
System.out.println(
"Message - "
+ stringDecryption(encryptedText,
key.toUpperCase()));
}
}
Python3
# Python program Implementing One Time Pad Algorithm
# Importing required classes
# Method 1
# Returning encrypted text
def stringEncryption(text, key):
# Initializing cipherText
cipherText = ""
# Initialize cipher array of key length
# which stores the sum of corresponding no.'s
# of plainText and key.
cipher = []
for i in range(len(key)):
cipher.append(ord(text[i]) - ord('A') + ord(key[i])-ord('A'))
# If the sum is greater than 25
# subtract 26 from it
# and store that resulting value
for i in range(len(key)):
if cipher[i] > 25:
cipher[i] = cipher[i] - 26
# Converting the no.'s into integers
# Convert these integers to corresponding
# characters and add them up to cipherText
for i in range(len(key)):
x = cipher[i] + ord('A')
cipherText += chr(x)
# Returning the cipherText
return cipherText
# Method 2
# Returning plain text
def stringDecryption(s, key):
# Initializing plain text
plainText = ""
# Initializing integer array of key length
# which stores difference
# of corresponding no.'s of
# each character of cipherText and key
plain = []
# Running for loop for each character
# subtracting and storing in the array
for i in range(len(key)):
plain.append(ord(s[i]) - ord('A') - (ord(key[i]) - ord('A')))
# If the difference is less than 0
# add 26 and store it in the array.
for i in range(len(key)):
if (plain[i] < 0):
plain[i] = plain[i] + 26
# Converting int to corresponding char
# add them up to plainText
for i in range(len(key)):
x = plain[i] + ord('A')
plainText += chr(x)
# Returning plainText
return plainText
plainText = "Hello"
# Declaring key
key = "MONEY"
# Converting plain text to toUpperCase
# function call to stringEncryption
# with plainText and key as parameters
encryptedText = stringEncryption(plainText.upper(), key.upper())
# Printing cipher Text
print("Cipher Text - " + encryptedText)
# Calling above method to stringDecryption
# with encryptedText and key as parameters
print("Message - " + stringDecryption(encryptedText, key.upper()))
# This code is contributed by Pranay Arora
C#
// C# program Implementing One Time Pad Algorithm
using System;
public class GFG {
public static String stringEncryption(String text,
String key)
{
// Initializing cipherText
String cipherText = "";
// Initialize cipher array of key length
// which stores the sum of corresponding no.'s
// of plainText and key.
int[] cipher = new int[key.Length];
for (int i = 0; i < key.Length; i++) {
cipher[i] = text[i] - 'A' + key[i] - 'A';
}
// If the sum is greater than 25
// subtract 26 from it
// and store that resulting value
for (int i = 0; i < key.Length; i++) {
if (cipher[i] > 25) {
cipher[i] = cipher[i] - 26;
}
}
// Converting the no.'s into integers
// Convert these integers to corresponding
// characters and add them up to cipherText
for (int i = 0; i < key.Length; i++) {
int x = cipher[i] + 'A';
cipherText += (char)x;
}
// Returning the cipherText
return cipherText;
}
// Method 2
// Returning plain text
public static String stringDecryption(String s,
String key)
{
// Initializing plain text
String plainText = "";
// Initializing integer array of key length
// which stores difference
// of corresponding no.'s of
// each character of cipherText and key
int[] plain = new int[key.Length];
// Running for loop for each character
// subtracting and storing in the array
for (int i = 0; i < key.Length; i++) {
plain[i] = s[i] - 'A' - (key[i] - 'A');
}
// If the difference is less than 0
// add 26 and store it in the array.
for (int i = 0; i < key.Length; i++) {
if (plain[i] < 0) {
plain[i] = plain[i] + 26;
}
}
// Converting int to corresponding char
// add them up to plainText
for (int i = 0; i < key.Length; i++) {
int x = plain[i] + 'A';
plainText += (char)x;
}
// Returning plainText
return plainText;
}
// Method 3
// Main driver method
static void Main()
{
// Declaring plain text
String plainText = "Hello";
// Declaring key
String key = "MONEY";
// Converting plain text to toUpperCase
// function call to stringEncryption
// with plainText and key as parameters
String encryptedText = stringEncryption(
plainText.ToUpper(), key.ToUpper());
// Printing cipher Text
Console.WriteLine("Cipher Text - " + encryptedText);
// Calling above method to stringDecryption
// with encryptedText and key as parameters
Console.WriteLine(
"Message - "
+ stringDecryption(encryptedText,
key.ToUpper()));
}
}
// This code is contributed by Pranay Arora
JavaScript
// Method 1
// Returning encrypted text
function stringEncryption(text, key) {
// Initializing cipherText
let cipherText = "";
// Initialize cipher array of key length
// which stores the sum of corresponding no.'s
// of plainText and key.
let cipher = [];
for (let i = 0; i < key.length; i++) {
cipher[i] = text.charCodeAt(i) - 'A'.charCodeAt(0) + key.charCodeAt(i) - 'A'.charCodeAt(0);
}
// If the sum is greater than 25
// subtract 26 from it
// and store that resulting value
for (let i = 0; i < key.length; i++) {
if (cipher[i] > 25) {
cipher[i] = cipher[i] - 26;
}
}
// Converting the no.'s into integers
// Convert these integers to corresponding
// characters and add them up to cipherText
for (let i = 0; i < key.length; i++) {
let x = cipher[i] + 'A'.charCodeAt(0);
cipherText += String.fromCharCode(x);
}
// Returning the cipherText
return cipherText;
}
// Method 2
// Returning plain text
function stringDecryption(s, key) {
// Initializing plain text
let plainText = "";
// Initializing integer array of key length
// which stores difference
// of corresponding no.'s of
// each character of cipherText and key
let plain = [];
// Running for loop for each character
// subtracting and storing in the array
for (let i = 0; i < key.length; i++) {
plain[i] = s.charCodeAt(i) - 'A'.charCodeAt(0) - (key.charCodeAt(i) - 'A'.charCodeAt(0));
}
// If the difference is less than 0
// add 26 and store it in the array.
for (let i = 0; i < key.length; i++) {
if (plain[i] < 0) {
plain[i] = plain[i] + 26;
}
}
// Converting int to corresponding char
// add them up to plainText
for (let i = 0; i < key.length; i++) {
let x = plain[i] + 'A'.charCodeAt(0);
plainText += String.fromCharCode(x);
}
// Returning plainText
return plainText;
}
// Method 3
// Main driver method
function main() {
// Declaring plain text
let plainText = "Hello";
// Declaring key
let key = "MONEY";
// Converting plain text to toUpperCase
// function call to stringEncryption
// with plainText and key as parameters
plainText = plainText.toUpperCase();
key = key.toUpperCase();
let encryptedText = stringEncryption(plainText, key);
// Printing cipher Text
console.log("Cipher Text - " + encryptedText);
// Calling above method to stringDecryption
// with encryptedText and key as parameters
console.log("Message - " + stringDecryption(encryptedText, key));
}
// Call the main function
main();
OutputCipher Text - TSYPM
Message - HELLO
Time Complexity: O(N)
Space Complexity: O(N)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem