using System; using System.Linq; using System.IO; using System.Text; using System.Collections.Generic; namespace AniNIX.Crypto { public class Caesarian : Cipher { public override String Description() { return "Caesarian ciphers shift letters by a numeric offset. Key format is thus a number."; } public override String Command() { return "caesar"; } public Caesarian(Workbench w) : base (w) {} /// /// Decode the user's input and relate to an existing function. /// /// The working copy of the cipher /// The original cipher /// The user input /// The modified workspace string public override String RunCommand(String workSpace,String inputText,String[] line) { if (workSpace == null || line == null || line.Length < 2) { Console.Error.WriteLine("Malformed request."); return workSpace; } switch (line[1]) { case "encrypt": return Encrypt(workSpace,inputText,line); case "decrypt": return Decrypt(workSpace,inputText,line); case "brute": BruteForce(workSpace); return workSpace; default: GetHelp(); return workSpace; } } /// /// Show this help text /// public override void GetHelp() { Console.WriteLine(String.Format("Help for the {0} cipher suite.\n{1}\n",Command(),Description())); Console.WriteLine("caesar encrypt key -- encrypt with the key\ncaesar decrypt key -- decrypt with the key\ncaesar brute -- brute-force for keys\ncaesar help -- show this helptext."); } /// /// Encrypt a string with the cipher /// /// The working copy of the cipher /// The original cipher /// The user input /// The encrypted string public override String Encrypt(String workSpace,String inputText,String[] line) { // Validate input if (line.Length != 3) { Console.Error.WriteLine("Bad formatting"); return workSpace; } int rotation = 0; try { rotation = Int32.Parse(line[2]); } catch (Exception e) { Console.Error.WriteLine("Error in parsing rotation value -- should be numeric."); Console.Error.WriteLine(e.Message); return workSpace; } char[] modified = workSpace.ToCharArray(); //For each character in the workSpace, rotate it by the offset given. for (int i = 0; i < modified.Length; i++) { if (Char.IsLetter(modified[i])) { int baseC; int modC; // Have to account for case. if (modified[i] < 'a') { baseC = (int)'A'; modC = (int)modified[i] - (int)'A'; } else { baseC = (int)'a'; modC = (int)modified[i] - (int)'a'; } modC = (modC + rotation)%26; modified[i] = (char)(baseC+modC); } } return new String(modified); } // This is a dummy override. public override String Decrypt(String workSpace,String inputText,String[] line) { return Encrypt(workSpace,inputText,line); } /// /// Try rotating through all 26 possible combinations. /// public void BruteForce(String workSpace) { String[] line = new String[3]; line[0] = "rot"; line[1] = "encrypt"; for (int i=0; i<26; i++) { line[2]=i.ToString(); Console.Write(String.Format("{0,2}: {1}\n",i,Encrypt(workSpace,null,line))); } } } }