Cifrado Vigenère

Vigenere Cipher es un método para cifrar texto alfabético. Utiliza una forma simple de sustitución polialfabética . Un cifrado polialfabético es cualquier cifrado basado en sustitución, utilizando múltiples alfabetos de sustitución. El cifrado del texto original se realiza mediante el cuadro Vigenère o tabla Vigenère .

  • La tabla consta de los alfabetos escritos 26 veces en diferentes filas, cada alfabeto desplazado cíclicamente hacia la izquierda en comparación con el alfabeto anterior, correspondiente a los 26 Cifrados César posibles .
  • En diferentes puntos del proceso de cifrado, el cifrado utiliza un alfabeto diferente de una de las filas.
  • El alfabeto utilizado en cada punto depende de una palabra clave repetitiva.

Ejemplo: 

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.

Cifrado:

La primera letra del texto sin formato, G, se empareja con A, la primera letra de la clave. Entonces use la fila G y la columna A del cuadrado de Vigenère, es decir, G. De manera similar, para la segunda letra del texto sin formato, se usa la segunda letra de la clave, la letra en la fila E, y la columna Y es C. El resto del el texto sin formato se cifra de manera similar. 

Tabla para encriptar – Geeks

Vigenère_square_shading

Descifrado:
el descifrado se realiza yendo a la fila de la tabla correspondiente a la clave, encontrando la posición de la letra del texto cifrado en esta fila y luego usando la etiqueta de la columna como texto sin formato. Por ejemplo, en la fila A (de AYUSH), el texto cifrado G aparece en la columna G, que es la primera letra del texto sin formato. A continuación, vamos a la fila Y (de AYUSH), localizamos el texto cifrado C que se encuentra en la columna E, por lo que E es la segunda letra del texto sin formato.

Una implementación más fácil podría ser visualizar Vigenère algebraicamente convirtiendo [AZ] en números [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

Nota: D i denota el desplazamiento del i-ésimo carácter del texto sin formato. Como compensación de A es 0 y de B es 1 y así sucesivamente.

A continuación se muestra la implementación de la 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 isi'nt
// 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";
 
    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

Python3

# 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 text
def 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 key
def 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 text
def 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 code
if __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#

// 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";
 
    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

<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 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";
 
 
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>
Producción

Ciphertext : GCYCZFMLYLEIM
Original/Decrypted Text : GEEKSFORGEEKS

Este artículo es una contribución de Ayush Khanduri . Si te gusta GeeksforGeeks y te gustaría contribuir, también puedes escribir un artículo usando write.geeksforgeeks.org o enviar tu artículo por correo a review-team@geeksforgeeks.org. Vea su artículo que aparece en la página principal de GeeksforGeeks y ayude a otros Geeks. 

Publicación traducida automáticamente

Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *