46. Vigenère cipher

The Vigenère cipher is only slightly more complicated than the Caesar cipher. The following method encrypts or decrypts a piece of plaintext and returns the resulting ciphertext:

// Use a Vigenere cipher to encrypt plaintext.
private static string VigenereEncryptDecrypt(this string plaintext,
string key, bool decrypt)
{
key = key.StripText();
plaintext = plaintext.StripText();

// Encrypt.
char[] chars = new char[plaintext.Length];
for (int i = 0; i < plaintext.Length; i++)
{
int shift = key[i % key.Length] - 'A';
if (decrypt) shift = -shift;
int ch = plaintext[i] - 'A';
ch = (ch + shift + 26) % 26;
chars[i] = (char)('A' + ch);
}
return new string(chars).ToFiveGrams();
}

This code calls the StripText method to remove non-letter characters as in the preceding solution. It then loops through the plaintext's letters.

For each letter, it uses the modulus operator (%) to get the matching character in the key word and subtracts the letter A from the key letter to get a shift value. If the method is decrypting, it negates the shift value. It then shifts the plaintext letter just as the preceding solution did. The method converts the ciphertext into five-grams and returns the result.

Download the CaesarCipher example solution to see additional details.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.201.217