对密钥进行暴力破解的仿射密码解密

Affine cipher decryption with bruteforce for keys

我想用 affine_algorithm 解密消息,从一开始就不知道密钥,我需要暴力破解它们才能找到正确的组合。在下面的代码中,解密的消息是不正确的,为了理解它,从中没有任何意义。我认为仿射方程有问题,我看到了一些其他带有 a_inverse 的代码,但我不知道如何在不知道密钥和暴力破解的情况下做到这一点。

#include<iostream>
#include<string.h>
#include<stdlib.h>
#include <string>
#include <fstream>
using namespace std;

int main(int argc, char **argv)
{
    ifstream myfile("C:\encr_affine.txt");
    string Ciphertext;

    while (myfile>>Ciphertext)
    {
        getline(myfile, Ciphertext);
    }

    for (int b = 1; b <= 25; b++)
    {

        for (int a = 1; a <= 25; a = a + 2)
        {
            if (a == 13)
                a = 15;

            string Msg = "";

            for (int i = 0; i < Ciphertext.length(); i++)
            {

                if (Ciphertext[i] != ' ')
                    Msg = Msg + (char)(((a * ((Ciphertext[i] - 'A' + b)) % 26)) + 'A');
                else
                    Msg += Ciphertext[i];
            }

            cout << "\n Key is : " << a << ", " << b << endl;
            cout << "Decr. message is : " << Msg << endl;

        }
    }
myfile.close();

}

经过一段时间,我找到了解决办法。我更改了文件阅读:

while (getline(myfile, Ciphertext))
    {
                //reading the ciphertext from the file
    }

然后我添加 a_inverse 等式:

for (int b = 1; b <= 25; b++)
    {

        for (int a = 1; a <= 25; a = a + 2)
        {
            if (a == 13)    //codition for only 12 a_keys
                a = 15;

            string Msg = "";
            int a_inv = 0;
            int flag = 0;

            for (int i = 0; i < 26; i++)
            {
                flag = (a * i) % 26;
                //Applying decryption formula a^-1
                //Check if (a*i)%26 == 1 ,then i will be the multiplicative inverse of a
                if (flag == 1)
                {
                    a_inv = i;
                }
            }

            for (int i = 0; i < Ciphertext.length(); i++)
            {
                toupper(Ciphertext[i]);

                if (Ciphertext[i] != ' ')       //if its "space" do your job!
                    Msg = Msg + (char)(((a_inv * ((Ciphertext[i] + 'A' - b)) % 26)) + 'A'); //affine equation 
                else
                    Msg += Ciphertext[i];       //if its "space" , let it!
            }

            cout << "\n Key is : " << a << ", " << b << endl;            //print keys and decrepted message
            cout << "Decr. message is : " << Msg << endl;

        }
    }

myfile.close();

}