Skip to content

Instantly share code, notes, and snippets.

@deus42
Created January 21, 2016 09:10
Show Gist options
  • Save deus42/deed07b0e158f519c797 to your computer and use it in GitHub Desktop.
Save deus42/deed07b0e158f519c797 to your computer and use it in GitHub Desktop.
Caesar Cipher - first well known cipher
public class CaesarCipher
{
private readonly int _shift;
private readonly char[] _alphabet;
public CaesarCipher(char[] alphabet, int shift = 2)
{
_alphabet = alphabet;
_shift = shift;
}
public string Encrypt(string plaintext)
{
string ciphertext = string.Empty;
foreach (var c in plaintext)
{
if (char.IsWhiteSpace(c))
{
ciphertext += c;
continue;
}
int index = (Array.IndexOf(_alphabet, c) + _shift + _alphabet.Length) % _alphabet.Length;
ciphertext += _alphabet[index];
}
return ciphertext;
}
public string Decrypt(string ciphertext)
{
string plaintext = string.Empty;
foreach (var c in ciphertext)
{
if (char.IsWhiteSpace(c))
{
plaintext += c;
continue;
}
int index = (Array.IndexOf(_alphabet, c) - _shift + _alphabet.Length) % _alphabet.Length;
plaintext += _alphabet[index];
}
return plaintext;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment