Created
January 21, 2016 09:10
-
-
Save deus42/deed07b0e158f519c797 to your computer and use it in GitHub Desktop.
Caesar Cipher - first well known cipher
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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