Vigenère Cipher

05 Jul, 2022
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 Vigenère square or Vigenè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 Vigenè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 Vigenè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 + 26) 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++
Java
Python3
C#
Javascript
// 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 isi'nt// equal to the length of original textstring 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 keystring 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 textstring 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 functionint main(){    string str = "GEEKSFORGEEKS";    string keyword = "AYUSH";     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 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 textstatic 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 keystatic 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 textstatic 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 casestatic 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 codepublic 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 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 textdef generateKey(string, key):    key = list(key)    if len(string) == len(key):        return(key)    else:        for i in range(len(string) -                       len(key)):            key.append(key[i % len(key)])    return("" . join(key))     # This function returns the# encrypted text generated# with the help of the keydef cipherText(string, key):    cipher_text = []    for i in range(len(string)):        x = (ord(string[i]) +             ord(key[i])) % 26        x += ord('A')        cipher_text.append(chr(x))    return("" . join(cipher_text))     # This function decrypts the# encrypted text and returns# the original textdef originalText(cipher_text, key):    orig_text = []    for i in range(len(cipher_text)):        x = (ord(cipher_text[i]) -             ord(key[i]) + 26) % 26        x += ord('A')        orig_text.append(chr(x))    return("" . join(orig_text))     # Driver codeif __name__ == "__main__":    string = "GEEKSFORGEEKS"    keyword = "AYUSH"    key = generateKey(string, keyword)    cipher_text = cipherText(string,key)    print("Ciphertext :", cipher_text)    print("Original/Decrypted Text :",           originalText(cipher_text, key)) # This code is contributed# by Pratik Somwanshi
// C# code to implement Vigenere Cipherusing System;     class GFG{ // This function generates the key in// a cyclic manner until it's length isi'nt// equal to the length of original textstatic 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 keystatic 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 textstatic 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 codepublic static void Main(String[] args){    String str = "GEEKSFORGEEKS";    String keyword = "AYUSH";     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 */
<script> // JavaScript code to implement Vigenere Cipher // This function generates the key in// a cyclic manner until it's length isi'nt// equal to the length of original textfunction 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 keyfunction 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 textfunction 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 casefunction 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 codelet str = "GEEKSFORGEEKS";let keyword = "AYUSH";  let key = generateKey(str, keyword); let cipher_text = cipherText(str, key); document.write("Ciphertext : "                   + cipher_text + "<br><br>"); document.write("Original/Decrypted Text : "                   + originalText(cipher_text, key)+"<br>");    // This code is contributed by rag2127 </script>
Ciphertext : GCYCZFMLYLEIM
Original/Decrypted Text : GEEKSFORGEEKS
This article is contributed by Ayush Khanduri. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. 
PratikSomwanshi
29AjayKumar
princiraj1992
Akanksha_Rai
Villan
anonymous007
rag2127
kumaripunam984122
UMADEVIRUCS18323
hardikkoriintern
cryptography
Strings
Technical Scripter
Strings
cryptography
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Length of the longest substring without repeating characters
Convert string to char array in C++
Check whether two strings are anagram of each other
Top 50 String Coding Problems for Interviews
Reverse words in a given string
What is Data Structure: Types, Classifications and Applications
Print all the duplicates in the input string
Reverse string in Python (6 different ways)
Remove duplicates from a given string
Array of Strings in C++ - 5 Different Ways to Create