Vigenere Cipher is a method of encrypting alphabetic text. It uses a simple form of polyalphabetic substitution. A polyalphabetic cipher is any cipher based on substitution, using multiple substitution alphabets. The encryption of the original text is done using the Vigenère square or Vigenère table.
- The table consists of the alphabets written out 26 times in different rows, each alphabet shifted cyclically to the left compared to the previous alphabet, corresponding to the 26 possible Caesar Ciphers.
- At different points in the encryption process, the cipher uses a different alphabet from one of the rows.
- The alphabet used at each point depends on a repeating keyword.
Example:
Input : Plaintext : GEEKSFORGEEKS
Keyword : AYUSH
Output : Ciphertext : GCYCZFMLYLEIM
For generating key, the given keyword is repeated
in a circular manner until it matches the length of
the plain text.
The keyword "AYUSH" generates the key "AYUSHAYUSHAYU"
The plain text is then encrypted using the process
explained below.
Encryption:
The first letter of the plaintext, G is paired with A, the first letter of the key. So use row G and column A of the Vigenère square, namely G. Similarly, for the second letter of the plaintext, the second letter of the key is used, the letter at row E, and column Y is C. The rest of the plaintext is enciphered in a similar fashion.
Table to encrypt - Geeks

Decryption:
Decryption is performed by going to the row in the table corresponding to the key, finding the position of the ciphertext letter in this row, and then using the column's label as the plaintext. For example, in row A (from AYUSH), the ciphertext G appears in column G, which is the first plaintext letter. Next, we go to row Y (from AYUSH), locate the ciphertext C which is found in column E, thus E is the second plaintext letter.
A more easy implementation could be to visualize Vigenère algebraically by converting [A-Z] into numbers [0–25].
Encryption
The plaintext(P) and key(K) are added modulo 26.
Ei = (Pi + Ki) mod 26
Decryption
Di = (Ei - Ki) mod 26
Note: Di denotes the offset of the i-th character of the plaintext. Like offset of A is 0 and of B is 1 and so on.
Below is the implementation of the idea.
C++
// C++ code to implement Vigenere Cipher
#include <bits/stdc++.h>
using namespace std;
// This function generates the key in
// a cyclic manner until it's length isn't
// equal to the length of original text
string generateKey(string str, string key)
{
int x = str.size();
for (int i = 0;; i++) {
if (x == i)
i = 0;
if (key.size() == str.size())
break;
key.push_back(key[i]);
}
return key;
}
// This function returns the encrypted text
// generated with the help of the key
string cipherText(string str, string key)
{
string cipher_text;
for (int i = 0; i < str.size(); i++) {
// converting in range 0-25
char x = (str[i] + key[i]) % 26;
// convert into alphabets(ASCII)
x += 'A';
cipher_text.push_back(x);
}
return cipher_text;
}
// This function decrypts the encrypted text
// and returns the original text
string originalText(string cipher_text, string key)
{
string orig_text;
for (int i = 0; i < cipher_text.size(); i++) {
// converting in range 0-25
char x = (cipher_text[i] - key[i] + 26) % 26;
// convert into alphabets(ASCII)
x += 'A';
orig_text.push_back(x);
}
return orig_text;
}
// Driver program to test the above function
int main()
{
string str = "GEEKSFORGEEKS";
string keyword = "AYUSH";
if (any_of(str.begin(), str.end(), ::islower))
transform(str.begin(), str.end(), str.begin(),
::toupper);
if (any_of(keyword.begin(), keyword.end(), ::islower))
transform(keyword.begin(), keyword.end(),
keyword.begin(), ::toupper);
string key = generateKey(str, keyword);
string cipher_text = cipherText(str, key);
cout << "Ciphertext : " << cipher_text << "\n";
cout << "Original/Decrypted Text : "
<< originalText(cipher_text, key);
return 0;
}
Java
// Java code to implement Vigenere Cipher
class GFG
{
// This function generates the key in
// a cyclic manner until it's length isi'nt
// equal to the length of original text
static String generateKey(String str, String key)
{
int x = str.length();
for (int i = 0; ; i++)
{
if (x == i)
i = 0;
if (key.length() == str.length())
break;
key+=(key.charAt(i));
}
return key;
}
// This function returns the encrypted text
// generated with the help of the key
static String cipherText(String str, String key)
{
String cipher_text="";
for (int i = 0; i < str.length(); i++)
{
// converting in range 0-25
int x = (str.charAt(i) + key.charAt(i)) %26;
// convert into alphabets(ASCII)
x += 'A';
cipher_text+=(char)(x);
}
return cipher_text;
}
// This function decrypts the encrypted text
// and returns the original text
static String originalText(String cipher_text, String key)
{
String orig_text="";
for (int i = 0 ; i < cipher_text.length() &&
i < key.length(); i++)
{
// converting in range 0-25
int x = (cipher_text.charAt(i) -
key.charAt(i) + 26) %26;
// convert into alphabets(ASCII)
x += 'A';
orig_text+=(char)(x);
}
return orig_text;
}
// This function will convert the lower case character to Upper case
static String LowerToUpper(String s)
{
StringBuffer str =new StringBuffer(s);
for(int i = 0; i < s.length(); i++)
{
if(Character.isLowerCase(s.charAt(i)))
{
str.setCharAt(i, Character.toUpperCase(s.charAt(i)));
}
}
s = str.toString();
return s;
}
// Driver code
public static void main(String[] args)
{
String Str = "GEEKSFORGEEKS";
String Keyword = "AYUSH";
String str = LowerToUpper(Str);
String keyword = LowerToUpper(Keyword);
String key = generateKey(str, keyword);
String cipher_text = cipherText(str, key);
System.out.println("Ciphertext : "
+ cipher_text + "\n");
System.out.println("Original/Decrypted Text : "
+ originalText(cipher_text, key));
}
}
// This code has been contributed by 29AjayKumar
Python
def generate_key(msg, key):
key = list(key)
if len(msg) == len(key):
return key
else:
for i in range(len(msg) - len(key)):
key.append(key[i % len(key)])
return "".join(key)
def encrypt_vigenere(msg, key):
encrypted_text = []
key = generate_key(msg, key)
for i in range(len(msg)):
char = msg[i]
if char.isupper():
encrypted_char = chr((ord(char) + ord(key[i]) - 2 * ord('A')) % 26 + ord('A'))
elif char.islower():
encrypted_char = chr((ord(char) + ord(key[i]) - 2 * ord('a')) % 26 + ord('a'))
else:
encrypted_char = char
encrypted_text.append(encrypted_char)
return "".join(encrypted_text)
def decrypt_vigenere(msg, key):
decrypted_text = []
key = generate_key(msg, key)
for i in range(len(msg)):
char = msg[i]
if char.isupper():
decrypted_char = chr((ord(char) - ord(key[i]) + 26) % 26 + ord('A'))
elif char.islower():
decrypted_char = chr((ord(char) - ord(key[i]) + 26) % 26 + ord('a'))
else:
decrypted_char = char
decrypted_text.append(decrypted_char)
return "".join(decrypted_text)
# Example usage
text_to_encrypt = "Hello, World!"
key = "KEY"
encrypted_text = encrypt_vigenere(text_to_encrypt, key)
print(f"Encrypted Text: {encrypted_text}")
decrypted_text = decrypt_vigenere(encrypted_text, key)
print(f"Decrypted Text: {decrypted_text}")
#previous code was only support the upper case letters
#this code can be apply on both
C#
// C# code to implement Vigenere Cipher
using System;
class GFG
{
// This function generates the key in
// a cyclic manner until it's length isi'nt
// equal to the length of original text
static String generateKey(String str, String key)
{
int x = str.Length;
for (int i = 0; ; i++)
{
if (x == i)
i = 0;
if (key.Length == str.Length)
break;
key+=(key[i]);
}
return key;
}
// This function returns the encrypted text
// generated with the help of the key
static String cipherText(String str, String key)
{
String cipher_text="";
for (int i = 0; i < str.Length; i++)
{
// converting in range 0-25
int x = (str[i] + key[i]) %26;
// convert into alphabets(ASCII)
x += 'A';
cipher_text+=(char)(x);
}
return cipher_text;
}
// This function decrypts the encrypted text
// and returns the original text
static String originalText(String cipher_text, String key)
{
String orig_text="";
for (int i = 0 ; i < cipher_text.Length &&
i < key.Length; i++)
{
// converting in range 0-25
int x = (cipher_text[i] -
key[i] + 26) %26;
// convert into alphabets(ASCII)
x += 'A';
orig_text+=(char)(x);
}
return orig_text;
}
// Driver code
public static void Main(String[] args)
{
String str = "GEEKSFORGEEKS";
String keyword = "AYUSH";
str = str.ToUpper();
keyword = keyword.ToUpper();
String key = generateKey(str, keyword);
String cipher_text = cipherText(str, key);
Console.WriteLine("Ciphertext : "
+ cipher_text + "\n");
Console.WriteLine("Original/Decrypted Text : "
+ originalText(cipher_text, key));
}
}
/* This code contributed by PrinciRaj1992 */
Javascript
// JavaScript code to implement Vigenere Cipher
// This function generates the key in
// a cyclic manner until it's length isn't
// equal to the length of original text
function generateKey(str,key)
{
key=key.split("");
if(str.length == key.length)
return key.join("");
else
{
let temp=key.length;
for (let i = 0;i<(str.length-temp) ; i++)
{
key.push(key[i % ((key).length)])
}
}
return key.join("");
}
// This function returns the encrypted text
// generated with the help of the key
function cipherText(str,key)
{
let cipher_text="";
for (let i = 0; i < str.length; i++)
{
// converting in range 0-25
let x = (str[i].charCodeAt(0) + key[i].charCodeAt(0)) %26;
// convert into alphabets(ASCII)
x += 'A'.charCodeAt(0);
cipher_text+=String.fromCharCode(x);
}
return cipher_text;
}
// This function decrypts the encrypted text
// and returns the original text
function originalText(cipher_text,key)
{
let orig_text="";
for (let i = 0 ; i < cipher_text.length ; i++)
{
// converting in range 0-25
let x = (cipher_text[i].charCodeAt(0) -
key[i].charCodeAt(0) + 26) %26;
// convert into alphabets(ASCII)
x += 'A'.charCodeAt(0);
orig_text+=String.fromCharCode(x);
}
return orig_text;
}
// This function will convert the lower
// case character to Upper case
function LowerToUpper(s)
{
let str =(s).split("");
for(let i = 0; i < s.length; i++)
{
if(s[i] == s[i].toLowerCase())
{
str[i] = s[i].toUpperCase();
}
}
s = str.toString();
return s;
}
// Driver code
let str = "GEEKSFORGEEKS";
let keyword = "AYUSH";
str = str.toUpperCase();
keyword = keyword.toUpperCase();
let key = generateKey(str, keyword);
let cipher_text = cipherText(str, key);
console.log("Ciphertext : "
+ cipher_text + "<br><br>");
console.log("Original/Decrypted Text : "
+ originalText(cipher_text, key)+"<br>");
OutputCiphertext : GCYCZFMLYLEIM
Original/Decrypted Text : GEEKSFORGEEKS
Time Complexity : O(n), where n is the length of the string(here str).
Space Complexity :O(n), here n is the length of the string(here str).
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