protected override bool keyIsValid(string key = null) { if (key == null) { key = this.Key; } string[] ab = key.Split(','); //"a,b",根据逗号分割字符串key,第一个数为乘数,第二个数为加数0 int aInt = int.Parse(ab[0]); return(NumberTheory.Gcd(aInt, Scheme.LetterSetSize) == 1); }
public override (string, bool) Decode(string cipher = null, string key = null) { if (cipher == null) { cipher = Cipher; } if (key == null) { key = Key; } if (!keyIsValid(key)) { return(null, false); } string[] ab = key.Split(','); //"a,b",根据逗号分割字符串key,第一个数为乘数,第二个数为加数0 int aInt = int.Parse(ab[0]); int bInt = int.Parse(ab[1]); string plain = ""; foreach (char c in cipher) { int p = c; if (c >= 'a' && c <= 'z') { if (NumberTheory.Gcd(aInt, Scheme.LetterSetSize) == 1) //只有当 a 与 n 互素的时候, a 才是有模逆的 { int cInt = (int)NumberTheory.Inverse(aInt, Scheme.LetterSetSize); p = (((c - 'a' - bInt) * cInt) % Scheme.LetterSetSize) + 'a'; } } else if (c >= 'A' && c <= 'Z') { if (NumberTheory.Gcd(aInt, Scheme.LetterSetSize) == 1) //只有当 a 与 n 互素的时候, a 才是有模逆的 { int cInt = (int)NumberTheory.Inverse(aInt, Scheme.LetterSetSize); p = (((c - 'A' - bInt) * cInt) % Scheme.LetterSetSize) + 'A'; } } plain += Convert.ToChar(p); } this.Key = key; this.Plain = plain; this.Cipher = cipher; return(plain, true); }
public override string GenerateKey() { Random rand = new Random(); int a = rand.Next(Scheme.LetterSetSize); while (NumberTheory.Gcd(a, Scheme.LetterSetSize) != 1) { a = rand.Next(Scheme.LetterSetSize); } string aString = Convert.ToString(a); string bString = rand.Next(Scheme.LetterSetSize).ToString(); string key = aString + "," + bString; return(key); }
public override (string, double) Break(string cipher = null) { if (cipher == null) { cipher = this.Cipher; } string plain = cipher; double maxProb = FrequencyAnalyst.Analyze(cipher); for (int i = 0; i < LetterSetSize; i++) { if (NumberTheory.Gcd(i, LetterSetSize) == 1) { for (int j = 0; j < LetterSetSize; j++) { string a = i.ToString(); string b = j.ToString(); string ab = a + "," + b; (string str, bool ok)result = Decode(cipher, ab); if (result.ok) { double prob = FrequencyAnalyst.Analyze(result.str); if (prob > maxProb) { plain = result.str; maxProb = prob; } } } } } this.Plain = plain; ProcessLog.Enqueue(plain); ProcessLog.Enqueue(""); return(plain, Math.Pow(Math.E, maxProb)); //throw new NotImplementedException(); }