/// <summary> /// Gets the CharacterFrequency for a character /// </summary> /// /// <param name="character">The character to get the frequency of</param> /// /// <returns>The character frequency of the character</returns> public CharacterFrequency GetFrequency(char character) { foreach (CharacterFrequency cf in characterFrequencies) //For each frequency in the list, { if (cf.Character == character) //If the characters are the same, { return(cf); //return the frequency } } //If we've reached here, then the list doesn't contain the character CharacterFrequency toRet = new CharacterFrequency(character); //Creates a frequency of 0 characterFrequencies.Add(toRet); //Adds to the list return(toRet); //Returns the newly created frequency }
public string BruteForce(string cipherText) { StringBuilder buff = new StringBuilder(); CharacterFrequencyList frequencies = fa.AnalyseFrequency(cipherText); //Get the character frequencies CharacterFrequency probablyE = frequencies.ProbablyE; // Character that is most likly to be E CharacterFrequency probablyT = frequencies.ProbablyT; // Character that is most likly to be T int p = alphabet.GetCharacterIndex('E'); //Get the index of E int q = alphabet.GetCharacterIndex('T'); //Get the index of T int r = alphabet.GetCharacterIndex(probablyE.Character); //Get the index of the ciphered E int s = alphabet.GetCharacterIndex(probablyT.Character); //Get the index of the ciphered T int D = Mod(p - q, 26); //Work out what D is (difference) int invD = Inverse(D); //Get the multiplicative inverse /* * Working out :D * a x indexOf('E') + b = indexOf ( probablyE ) MOD 26, indexOf(e) = p, indexOf( probablyE ) = r * a x indexOf('T') + b = indexOf ( probablyT ) MOD 26, indexOf(t) = q, indexOf( probablyT ) = s * * D = p - q; * * a = D^-1 (r-s) MOD 26 * b = D^-1 (ps - qr) MOD 26 */ int a = Mod(invD * (r - s), 26); //Work out the first part of the key (a) int b = Mod(invD * ((p * s) - (q * r)), 26); //Work out the second part of the key (b) Console.WriteLine("Found key: a={0}, b={1}", a, b); buff.Append(string.Format("Key: ({0},{1}) ", a, b)); buff.Append(string.Format("\nDeciphered Text:\n{0}", Decipher(cipherText, a, b))); return(buff.ToString()); //Return the deciphered message }
/// <summary> /// Adds 1 to the frequency of the character /// </summary> /// /// <param name="character">Character to add 1 to the frequency of</param> public void AddTo(char character) { CharacterFrequency cf = GetFrequency(character); //Get the current frequency (0 if it didn't exist) cf.Frequency++; //Add 1 to it }