El cifrado de palabras clave es una forma de sustitución monoalfabética . Se utiliza una palabra clave como clave y determina las coincidencias de letras del alfabeto cifrado con el alfabeto simple. Se eliminan las repeticiones de letras en la palabra, luego se genera el alfabeto cifrado con la palabra clave que coincide con A, B, C, etc. hasta que se agota la palabra clave, después de lo cual el resto de las letras del texto cifrado se usan en orden alfabético, excluyendo aquellas ya utilizado en la clave.
Cifrado:
La primera línea de entrada contiene la palabra clave que desea ingresar. La segunda línea de entrada contiene la string que debe cifrar.
Plaintext: A B C D E F G H I J K L M N O P Q R S T U V W X Y Z Encrypted: K R Y P T O S A B C D E F G H I J L M N Q U V W X Z
Con KRYPTOS como palabra clave, todas las A se convierten en K, todas las B se convierten en R, y así sucesivamente. Encriptando el mensaje «el conocimiento es poder» usando la palabra clave «Kryptos»:
Encrypting the message: Knowledge is Power Encoded message: IlmWjbaEb GQ NmWbp
Ejemplos:
Input : Keyword : secret Message : Zombie Here Output : Ciphered String : ZLJEFT DTOT
Take the first example, we used "secret" keyword there. Plain Text : A B C D E F G H I J K L M N O P Q R S T U V W X Y Z When "secret" keyword is used, the new encrypting text becomes : Encrypting : S E C R T A B D F G H I J K L M N O P Q U V W X Y Z This means 'A' means 'S', 'B' means 'E' and 'C' means 'C' and so on. Lets encode the given message "Zombie Here" ZOMBIE HERE becomes ZLJEFT DTOT
Input : Keyword : Star War Message : Attack at dawn Output : Ciphered String : SPPSAG SP RSVJ
Algunos puntos a tener en cuenta en este método:
- Todos los mensajes están codificados en mayúsculas.
- Los espacios en blanco, los caracteres especiales y los números no tienen en cuenta las palabras clave, aunque puede incluirlos allí.
- Mientras se encripta el mensaje, los espacios en blanco, los caracteres especiales y los números no se ven afectados.
A continuación se muestra la implementación:
C++
// CPP program for encoding the string // using classical cipher #include<bits/stdc++.h> using namespace std; // Function generates the encoded text string encoder(string key) { string encoded = ""; // This array represents the // 26 letters of alphabets bool arr[26] = {0}; // This loop inserts the keyword // at the start of the encoded string for (int i=0; i<key.size(); i++) { if(key[i] >= 'A' && key[i] <= 'Z') { // To check whether the character is inserted // earlier in the encoded string or not if (arr[key[i]-65] == 0) { encoded += key[i]; arr[key[i]-65] = 1; } } else if (key[i] >= 'a' && key[i] <= 'z') { if (arr[key[i]-97] == 0) { encoded += key[i] - 32; arr[key[i]-97] = 1; } } } // This loop inserts the remaining // characters in the encoded string. for (int i=0; i<26; i++) { if(arr[i] == 0) { arr[i]=1; encoded += char(i + 65); } } return encoded; } // Function that generates encodes(cipher) the message string cipheredIt(string msg, string encoded) { string cipher=""; // This loop ciphered the message. // Spaces, special characters and numbers remain same. for (int i=0; i<msg.size(); i++) { if (msg[i] >='a' && msg[i] <='z') { int pos = msg[i] - 97; cipher += encoded[pos]; } else if (msg[i] >='A' && msg[i] <='Z') { int pos = msg[i] - 65; cipher += encoded[pos]; } else { cipher += msg[i]; } } return cipher; } // Driver code int main() { // Hold the Keyword string key; key = "Computer"; cout << "Keyword : " <<key << endl; // Function call to generate encoded text string encoded = encoder(key); // Message that need to encode string message = "GeeksforGeeks"; cout << "Message before Ciphering : " << message << endl; // Function call to print ciphered text cout << "Ciphered Text : " << cipheredIt(message,encoded) << endl; return 0; }
Java
// Java program for encoding the string // using classical cipher class GFG { // Function generates the encoded text static String encoder(char[] key) { String encoded = ""; // This array represents the // 26 letters of alphabets boolean[] arr = new boolean[26]; // This loop inserts the keyword // at the start of the encoded string for (int i = 0; i < key.length; i++) { if (key[i] >= 'A' && key[i] <= 'Z') { // To check whether the character is inserted // earlier in the encoded string or not if (arr[key[i] - 65] == false) { encoded += (char) key[i]; arr[key[i] - 65] = true; } } else if (key[i] >= 'a' && key[i] <= 'z') { if (arr[key[i] - 97] == false) { encoded += (char) (key[i] - 32); arr[key[i] - 97] = true; } } } // This loop inserts the remaining // characters in the encoded string. for (int i = 0; i < 26; i++) { if (arr[i] == false) { arr[i] = true; encoded += (char) (i + 65); } } return encoded; } // Function that generates encodes(cipher) the message static String cipheredIt(String msg, String encoded) { String cipher = ""; // This loop ciphered the message. // Spaces, special characters and numbers remain same. for (int i = 0; i < msg.length(); i++) { if (msg.charAt(i) >= 'a' && msg.charAt(i) <= 'z') { int pos = msg.charAt(i) - 97; cipher += encoded.charAt(pos); } else if (msg.charAt(i) >= 'A' && msg.charAt(i) <= 'Z') { int pos = msg.charAt(i) - 65; cipher += encoded.charAt(pos); } else { cipher += msg.charAt(i); } } return cipher; } // Driver code public static void main(String[] args) { // Hold the Keyword String key; key = "Computer"; System.out.println("Keyword : " + key); // Function call to generate encoded text String encoded = encoder(key.toCharArray()); // Message that need to encode String message = "GeeksforGeeks"; System.out.println("Message before Ciphering : " + message); // Function call to print ciphered text System.out.println("Ciphered Text : " + cipheredIt(message, encoded)); } } // This code is contributed by 29AjayKumar
C#
// C# program for encoding the string // using classical cipher using System; class GFG { // Function generates the encoded text static String encoder(char[] key) { String encoded = ""; // This array represents the // 26 letters of alphabets Boolean[] arr = new Boolean[26]; // This loop inserts the keyword // at the start of the encoded string for (int i = 0; i < key.Length; i++) { if (key[i] >= 'A' && key[i] <= 'Z') { // To check whether the character is inserted // earlier in the encoded string or not if (arr[key[i] - 65] == false) { encoded += (char) key[i]; arr[key[i] - 65] = true; } } else if (key[i] >= 'a' && key[i] <= 'z') { if (arr[key[i] - 97] == false) { encoded += (char) (key[i] - 32); arr[key[i] - 97] = true; } } } // This loop inserts the remaining // characters in the encoded string. for (int i = 0; i < 26; i++) { if (arr[i] == false) { arr[i] = true; encoded += (char) (i + 65); } } return encoded; } // Function that generates encodes(cipher) the message static String cipheredIt(String msg, String encoded) { String cipher = ""; // This loop ciphered the message. // Spaces, special characters and numbers remain same. for (int i = 0; i < msg.Length; i++) { if (msg[i] >= 'a' && msg[i] <= 'z') { int pos = msg[i] - 97; cipher += encoded[pos]; } else if (msg[i] >= 'A' && msg[i] <= 'Z') { int pos = msg[i] - 65; cipher += encoded[pos]; } else { cipher += msg[i]; } } return cipher; } // Driver code public static void Main(String[] args) { // Hold the Keyword String key; key = "Computer"; Console.WriteLine("Keyword : " + key); // Function call to generate encoded text String encoded = encoder(key.ToCharArray()); // Message that need to encode String message = "GeeksforGeeks"; Console.WriteLine("Message before Ciphering : " + message); // Function call to print ciphered text Console.WriteLine("Ciphered Text : " + cipheredIt(message, encoded)); } } /* This code contributed by PrinciRaj1992 */
Javascript
<script> // JavaScript program for encoding the string // using classical cipher // Function generates the encoded text function encoder(key) { let encoded = ""; // This array represents the // 26 letters of alphabets let arr = new Array(26); for(let i=0;i<26;i++) { arr[i]=false; } // This loop inserts the keyword // at the start of the encoded string for (let i = 0; i < key.length; i++) { if (key[i].charCodeAt(0) >= 'A'.charCodeAt(0) && key[i].charCodeAt(0) <= 'Z'.charCodeAt(0)) { // To check whether the character is inserted // earlier in the encoded string or not if (arr[key[i].charCodeAt(0) - 65] == false) { encoded += ( key[i]); arr[key[i].charCodeAt(0) - 65] = true; } } else if (key[i].charCodeAt(0) >= 'a'.charCodeAt(0) && key[i].charCodeAt(0) <= 'z'.charCodeAt(0)) { if (arr[key[i].charCodeAt(0) - 97] == false) { encoded += String.fromCharCode(key[i].charCodeAt(0) - 32); arr[key[i].charCodeAt(0) - 97] = true; } } } // This loop inserts the remaining // characters in the encoded string. for (let i = 0; i < 26; i++) { if (arr[i] == false) { arr[i] = true; encoded += String.fromCharCode(i + 65); } } return encoded; } // Function that generates encodes(cipher) the message function cipheredIt(msg,encoded) { let cipher = ""; // This loop ciphered the message. // Spaces, special characters and numbers remain same. for (let i = 0; i < msg.length; i++) { if (msg[i] >= 'a' && msg[i] <= 'z') { let pos = msg[i].charCodeAt(0) - 97; cipher += encoded[pos]; } else if (msg[i] >= 'A' && msg[i] <= 'Z') { let pos = msg[i].charCodeAt(0) - 65; cipher += encoded[pos]; } else { cipher += msg[i]; } } return cipher; } // Driver code // Hold the Keyword let key; key = "Computer"; document.write("Keyword : " + key+"<br>"); // Function call to generate encoded text let encoded = encoder(key.split("")); // Message that need to encode let message = "GeeksforGeeks"; document.write("Message before Ciphering : " + message+"<br>"); // Function call to print ciphered text document.write("Ciphered Text : " + cipheredIt(message, encoded)); // This code is contributed by rag2127 </script>
Python3
# Python program for encoding the string # using classical cipher import string # stores all upper case alphabets all_alphabets = list(string.ascii_uppercase) keyword = "Star War" keyword1 = keyword.upper() message = "Attack at dawn" # converts message to list msg = [] for i in message: msg.append(i.upper()) # removes default elements def duplicates(list): key = [] for i in list: if i not in key: key.append(i) return key keyword1 = duplicates(keyword1) # Stores the encryption list encrypting = duplicates(keyword1+all_alphabets) # removes spaces from the encryption list for i in encrypting: if(i == ' '): encrypting.remove(' ') ciphertext = "" # maps each element of the message to the encryption list and stores it in ciphertext for i in range(len(msg)): if(msg[i] != ' '): ciphertext = ciphertext+encrypting[all_alphabets.index(msg[i])] else: ciphertext = ciphertext+' ' print("Keyword : ", keyword) print("Message before Ciphering : ", message) print("Ciphered Text : ", ciphertext) # This code is contributed by Pranay Arora
Keyword : Computer Message before Ciphering : GeeksforGeeks Ciphered Text : EUUDNTILEUUDN
Descifrado:
Para decodificar el mensaje, verifica la posición del mensaje dado en el texto cifrado con el texto sin formato.
Plaintext: A B C D E F G H I J K L M N O P Q R S T U V W X Y Z Encrypted: K R Y P T O S A B C D E F G H I J L M N Q U V W X Z
Message: PTYBIATLEP Deciphered Text: DECIPHERED
Ahora, ¿cómo generamos la string descifrada ? Buscamos ‘P’ en Texto cifrado y comparamos su posición con la letra de texto sin formato y generamos esa letra. Entonces ‘P’ se convierte en ‘D’, ‘T’ se convierte en ‘E’, ‘Y’ se convierte en ‘C’, y así sucesivamente.
Ejemplos:
Input : Keyword : secret Message : zljeft dtOT Output : Deciphered String : ZOMBIE HERE Input : Keyword : joker0O7hack123 Message : QjTijl Output : Deciphered String : BATMAN
A continuación se muestra la implementación:
Ejemplo 1
CPP
// CPP program for decoding the string // which generate using classical cipher #include <bits/stdc++.h> using namespace std; // Original Set of letters string plaintext = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // Function generates the encoded text string encoder(string key) { string encoded = ""; bool arr[26] = { 0 }; // This loop inserts the keyword // at the start of the encoded string for (int i = 0; i < key.size(); i++) { if (key[i] >= 'A' && key[i] <= 'Z') { // To check whether the character is inserted // earlier in the encoded string or not if (arr[key[i] - 65] == 0) { encoded += key[i]; arr[key[i] - 65] = 1; } } else if (key[i] >= 'a' && key[i] <= 'z') { if (arr[key[i] - 97] == 0) { encoded += key[i] - 32; arr[key[i] - 97] = 1; } } } // This loop inserts the remaining // characters in the encoded string. for (int i = 0; i < 26; i++) { if (arr[i] == 0) { arr[i] = 1; encoded += char(i + 65); } } return encoded; } // This function will decode the message string decipheredIt(string msg, string encoded) { // Hold the position of every character (A-Z) // from encoded string map<char, int> enc; for (int i = 0; i < encoded.size(); i++) { enc[encoded[i]] = i; } string decipher = ""; // This loop deciphered the message. // Spaces, special characters and numbers remain same. for (int i = 0; i < msg.size(); i++) { if (msg[i] >= 'a' && msg[i] <= 'z') { int pos = enc[msg[i] - 32]; decipher += plaintext[pos]; } else if (msg[i] >= 'A' && msg[i] <= 'Z') { int pos = enc[msg[i]]; decipher += plaintext[pos]; } else { decipher += msg[i]; } } return decipher; } // Driver code int main() { // Hold the Keyword string key; key = "Computer"; cout << "Keyword : " << key << endl; // Function call to generate encoded text string encoded = encoder(key); // Message that need to decode string message = "EUUDN TIL EUUDN"; cout << "Message before Deciphering : " << message << endl; // Function call to print deciphered text cout << "Ciphered Text : " << decipheredIt(message, encoded) << endl; return 0; }
Java
// Java program for decoding the string // using classical cipher import java.util.HashMap; import java.util.Map; class GFG { // Function generates the encoded text public static String encoder(char[] key) { String encoded = ""; // This array represents the // 26 letters of alphabets boolean[] arr = new boolean[26]; // This loop inserts the keyword // at the start of the encoded string for (int i = 0; i < key.length; i++) { if (key[i] >= 'A' && key[i] <= 'Z') { // To check whether the character is inserted // earlier in the encoded string or not if (arr[key[i] - 65] == false) { encoded += (char) key[i]; arr[key[i] - 65] = true; } } else if (key[i] >= 'a' && key[i] <= 'z') { if (arr[key[i] - 97] == false) { encoded += (char) (key[i] - 32); arr[key[i] - 97] = true; } } } // This loop inserts the remaining // characters in the encoded string. for (int i = 0; i < 26; i++) { if (arr[i] == false) { arr[i] = true; encoded += (char) (i + 65); } } return encoded; } // This function will decode the message public static String decipheredIt(String msg, String input) { // Original Set of letters String plaintext = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; String decipher = ""; // Hold the position of every character (A-Z) from encoded string Map<Character, Integer> enc = new HashMap<>(); for (int i = 0; i < input.length(); i++) { enc.put(input.charAt(i), i); } // This loop deciphered the message. // Spaces, special characters and numbers remain same. for (int i = 0; i < msg.length(); i++) { if (msg.charAt(i) >= 'a' && msg.charAt(i) <= 'z') { int pos = enc.get((char)(msg.charAt(i)-32)); decipher += plaintext.charAt(pos); } else if (msg.charAt(i) >= 'A' && msg.charAt(i) <= 'Z') { int pos = enc.get(msg.charAt(i)); decipher += plaintext.charAt(pos); } else { decipher += msg.charAt(i); } } return decipher; } // Driver code public static void main(String[] args) { // Hold the Keyword String key; key = "Computer"; System.out.println("Keyword : " + key); // Function call to generate encoded text String decoded = encoder(key.toCharArray()); // Message that need to encode String message = "EUUDN TIL EUUDN"; System.out.println("Message before Deciphering : " + message); // Function call to print ciphered text System.out.println("Ciphered Text : " + decipheredIt(message, decoded)); } } // This code is contributed by javierdsv
Keyword : Computer Message before Deciphering : EUUDN TIL EUUDN Ciphered Text : GEEKS FOR GEEKS
Ejemplo 2
Python
# Python Program for Decoding the String # using Classical Cipher import string # stores all upper case alphabets all_alphabets = list(string.ascii_uppercase) keyword = "Star War" keyword1 = keyword.upper() ciphertext = "SPPSAG SP RSVJ" # converts message to list ct = [] for i in ciphertext: ct.append(i.upper()) # removes default elements def duplicates(list): key = [] for i in list: if i not in key: key.append(i) return key keyword1 = duplicates(keyword1) # Stores the encryption list encrypting = duplicates(keyword1+all_alphabets) # removes spaces from the encryption list for i in encrypting: if(i == ' '): encrypting.remove(' ') # maps each element of the message to the encryption list and stores it in ciphertext message = "" for i in range(len(ct)): if(ct[i] != ' '): message = message+all_alphabets[encrypting.index(ct[i])] else: message = message+' ' print("Keyword : ", keyword) print("Ciphered Text : ", ciphertext) print("Message before Ciphering : ", message)
('Keyword : ', 'Star War') ('Ciphered Text : ', 'SPPSAG SP RSVJ') ('Message before Ciphering : ', 'ATTACK AT DAWN')
Nota: También se puede mejorar este cifrado clásico: palabra clave. Aquí solo estamos tomando AZ en texto sin formato. También puede tener en cuenta mayúsculas, minúsculas y números.
Formas de atacar un cifrado de palabra clave:
Las mejores formas de atacar un cifrado de palabra clave sin conocer la palabra clave son a través del ataque de texto sin formato conocido , el análisis de frecuencia y el descubrimiento de la palabra clave (a menudo, un criptoanalista combinará las tres técnicas). El descubrimiento de palabras clave permite el descifrado inmediato ya que la tabla se puede hacer de inmediato.
Este artículo es una contribución de Sachin Bisht . 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