Basic Cryptography – The Vigenere Cipher
eric.mann.blog
eric.mann.blog
* If key is the same length as plaintext, and truly random, that's a One-Time Pad.
* If the message is appended to the seed key, that's an Autokey Cipher.
* If the key is repeated (what the PHP does but not made clear), that's classical Vigenere.
It also doesn't describe breaking them:
* OTPs are unbreakable.
* You can break Autokey by using crib words (e.g. "the") at different locations of the ciphertext, selecting the most phonetically plausible and working backwards to recover the earlier plaintext.
* Vigenere can be attacked by trying the same shift for every Nth letter, or using cribs.
A very simple optimization is to use encrypt function to decrypt the encrypted message by providing the "inverse key" as parameter, which is a 2 line function altogether. Implementation of said implementation is left as an exercise for the reader.
private static char encipherCharacter(char message_char, char key_char){
return (char)(((int)(message_char) + (int)(key_char) - 194)%26 + 97);
}
public static String encipher(String plaintext, String key){
String ciphertext = "";
for(int i = 0; i < plaintext.length(); i++)
ciphertext += encipherCharacter(plaintext.charAt(i), key.charAt((i % key.length())));
return ciphertext;
}
I'd love to see other implementations, if anyone has some to share.https://gist.github.com/ctrezevant/8ca9e163d702af245ded35d97...
string Vigenere(string text, string key) => string.Join("", text.Select((p, k) => p < 'A' || p > 'Z' ? p : (char)((p + key[k % key.Length]) % 26 + 85)));This is like asking a child doing writing exercises, “Why on Earth would you rewrite the same letter over and over again?”
Could have just used a mod operator to cycle around the key.