private int _m, _s, _mod;
public Affine(int m, int s, string alpha)
this._mod = alpha.Length;
public string Encrypt(string text)
if (string.IsNullOrWhiteSpace(text))
throw new Exception("Cannot encrypt an empty string you silly fool!");
var textArray = text.ToCharArray();
var cipher = new StringBuilder();
foreach (var c in textArray)
var v = (((this._alpha.IndexOf(c) * this._m) + this._s) % _mod);
cipher.Append(this._alpha[v]);
return cipher.ToString();
public string Decrypt(string text)
if (string.IsNullOrWhiteSpace(text))
throw new Exception("Cannot encrypt an empty string you silly fool!");
var textArray = text.ToCharArray();
var plain = new StringBuilder();
foreach (var c in textArray)
var v = (((this._alpha.IndexOf(c) * this._m) + this._s) % _mod);
plain.Append(this._alpha[v]);
static string atoz = "abcdefghijklmnopqrstuvwxyz";
static string plainText = "howareyou";
static char[] plain = plainText.ToCharArray();
public static void Main()
var affine = new Affine(5, 7, "abcdefghijklmnopqrstuvwxyz");
Console.WriteLine(affine.Encrypt("howareyou"));
var encrypted = string.Empty;
var decrypted = string.Empty;
Console.WriteLine("---------------------------------");
Console.WriteLine("Original: " + c);
Console.WriteLine("Map: " + v);
Console.WriteLine("Encrypted: " + atoz[e]);
Console.WriteLine("Decrypted: " + atoz[d]);
Console.WriteLine("---------------------------------");
Console.WriteLine("Encrypted: " + encrypted);
Console.WriteLine("Decrypted: " + decrypted);
public static int encrypt(int c)
return (((c * 5) + 7) % 26);
public static int decrypt(int c)
var x = (((c + -7) * 21) % 26);