4. Ceaser Cipher
1.1 Ceaser Cipher
The Caesar cipher, also known as a shift cipher, is one of the simplest forms of
encryption. It is a substitution cipher where each letter in the original message
(called the plaintext) is replaced with a letter corresponding to a certain number
of letters up.
1.2 Algorithm
public static class Ceaser
{
public static string Encrypt(string plainText, int shift)
{
return CeaserAlgorithm(plainText, shift);
}
public static string Decrypt(string cipheredText, int shift)
{
return CeaserAlgorithm(cipheredText, shift * -1);
}
private static bool IsLetter(char letter)
{
return char.IsLetter(letter);
}
private static string CeaserAlgorithm(string text, int shift)
{
var buffer = text.ToCharArray();
for (var i = 0; i < buffer.Length; i++)
{
var letter = buffer[i];
if (!IsLetter(letter))
{
buffer[i] = ' ';
}
else
{
letter = (char)(letter + shift);
if (IsOverFlow(letter))
letter = (char)(letter - 26);
else if (IsUnderFlow(letter))
letter = (char)(letter + 26);
buffer[i] = letter;
}
}
return new string(buffer);
}
private static bool IsOverFlow(char letter)
{
return letter > 'z';
}
private static bool IsUnderFlow(char letter)
{
return letter < 'a';
}
}
6. Vigenere Cipher
2.1 Vigenere Cipher
The Vigenere cipher is a method of encrypting alphabetic text by using a series
of different Caesar ciphers based on the letters of a keyword. It is a simple form
of polyalphabetic substitution.
2.2 Algorithm
public static class Vigenere
{
private static string Algorithm(string input, string key, bool encipher)
{
if (key.Any(t => !IsLetter(t)))
return null;
var result = string.Empty;
var nonAlphaCharCount = 0;
for (var i = 0; i < input.Length; ++i)
{
if (IsLetter(input[i]))
{
var offset = 'a';
if (IsUpperLetter(input[i]))
offset = 'A';
var keyIndex = (i - nonAlphaCharCount) % key.Length;
var k = (IsUpperLetter(input[i]) ? char.ToUpper(key[keyIndex]) :
char.ToLower(key[keyIndex])) - offset;
k = encipher ? k : -k;
var ch = (char)(Mod(input[i] + k - offset, 26) + offset);
result += ch;
}
else
{
result += input[i];
++nonAlphaCharCount;
}
}
return result;
}
private static bool IsUpperLetter(char c)
{
return char.IsUpper(c);
}
private static bool IsLetter(char letter)
{
return char.IsLetter(letter);
}
public static string Encrypt(string input, string key)
{
return Algorithm(input, key, true);
}
public static string Decrypt(string input, string key)
{
return Algorithm(input, key, false);
}
private static int Mod(int a, int b)
{
return (a % b + b) % b;
}
}