Created
August 5, 2016 15:32
-
-
Save coldacid/89c32a976c90a9b69e72e4f73d9a6e56 to your computer and use it in GitHub Desktop.
Pivoting Caesar 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
// Copyright (c) 2016 Christopher S. Charabaruk <chris.charabaruk%%outlook.com> | |
public class PivotCaesar | |
{ | |
public static void Main(string[] args) | |
{ | |
if (args[0] == "-d" || args[0] == "--decrypt") | |
{ | |
foreach (var message in args.Skip(1)) | |
{ | |
Console.Write("Cipher: \"{0}\"\n", message); | |
Console.Write("Clear: \"{0}\"\n\n", Decrypt(message)); | |
} | |
} | |
else | |
{ | |
var original = string.Join(" ", args); | |
var clear = original.ToUpperInvariant().Replace(".", ".."); | |
clear = (new Regex(@"[^A-Z0-9\.]")).Replace(clear, "."); | |
Console.Write("Original: \"{0}\"\n", original); | |
Console.Write("Clear: \"{0}\"\n", clear); | |
Console.Write("Cipher: \"{0}\"\n", Encrypt(clear)); | |
} | |
} | |
public static string Encrypt(string cleartext) | |
{ | |
var pivot = InitialPivot; | |
var ciphertext = new StringBuilder(cleartext.Length); | |
foreach (var c in cleartext.ToCharArray()) | |
{ | |
var pos = (Alphabet.IndexOf(c) + pivot) % AlphabetLength; | |
if (pos == 0) pos = AlphabetLength; | |
ciphertext.Append(Alphabet[pos]); | |
if (Pivots.Keys.Contains(c)) | |
{ | |
pivot = (pivot + Pivots[c]) % AlphabetLength; | |
if (pivot == 0) pivot = InitialPivot; | |
} | |
} | |
return ciphertext.ToString(); | |
} | |
public static string Decrypt(string ciphertext) | |
{ | |
var pivot = InitialPivot; | |
var cleartext = new StringBuilder(ciphertext.Length); | |
foreach (var c in ciphertext.ToString().ToCharArray()) | |
{ | |
var pos = (Alphabet.IndexOf(c) - pivot); | |
if (pos <= 0) pos += AlphabetLength; | |
var cc = Alphabet[pos]; | |
cleartext.Append(cc); | |
if (Pivots.Keys.Contains(cc)) | |
{ | |
pivot = (pivot + Pivots[cc]) % AlphabetLength; | |
if (pivot == 0) pivot = InitialPivot; | |
} | |
} | |
return cleartext.ToString(); | |
} | |
public static readonly List<char> Alphabet = ("\0" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.") | |
.ToCharArray() | |
.ToList(); | |
public static readonly int AlphabetLength = Alphabet.Count - 1; | |
public static readonly Dictionary<char, int> Pivots = new Dictionary<char, int> | |
{ | |
{ 'A', 2 }, | |
{ 'E', 3 }, | |
{ 'I', 5 }, | |
{ 'O', 7 }, | |
{ 'U', 11 }, | |
{ '0', 13 }, | |
{ '.', 17 } | |
}; | |
public static readonly int InitialPivot = 19; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment