string S, K, generated;
cout << "Enter the message: ";
cin >> S;
cout << "Enter the key: ";
cin >> K;
cout << "The message is: " << S << endl; // output the string
int seed = 0;
for(int i = 0; i < (int) K.length(); i++)
    seed += K[i]; // used to generate a certain sequence of numbers
srand(seed); // new seed per new key
cout << "The cipher is: ";
for(int i = 0; i < (int) S.length(); i++) {
    int R = rand() % K.length();
    char L = 65 + (S[i] - 65 + K[R] - 65) % 26;
    cout << L;
    generated += L; // to actually have something to use for decryption
}
// FINALLY, to reach to this step and do something like this took me over 2 hours of continuous debugging
cout << endl;
cout << "The message again is: ";
for(int i = 0; i < (int) generated.length(); i++) {
    int R = rand() % K.length();
    char L = 65 + (generated[i] - 65 + K[R] - 65) % 26;
    cout << L;
}
cout << endl;

抱歉,代码困惑。无论如何,这就是我到目前为止所做的事情:
  • 用户插入消息和密钥
  • 用户获得密文

  • 但是现在,我实际上仍然坚持想要使用正确的密钥解密密文的事实。基本上,我想将密文恢复为纯文本。我自己努力完成此工作,但此方法列在“消息再次是:”下,但这给了我错误的结果。

    我在这里做错了什么?

    最佳答案

    该代码很奇怪,但实际上可以工作。前提是编码器和解码器由同一编译器制造,并且可能在同一台计算机上。

    您正在使用密钥生成srand的种子。该种子可以繁殖。进行中的随机数将是可预测的。

    解码消息时,应该使用相同的种子再次使用srand

    int main()
    {
        string S, K, generated;
        S = "MESSAGE";
        K = "KEY";
        cout << "The message is: " << S << endl; // output the string
    
        {
            int seed = 0;
            for (int i = 0; i < (int)K.length(); i++)
                seed += K[i]; // used to generate a certain sequence of numbers
            srand(seed); // new seed per new key
        }
    
        cout << "The cipher is: ";
        for (int i = 0; i < (int)S.length(); i++)
        {
            int R = rand() % K.length();
            char L = 65 + (S[i] - 65 + K[R] - 65) % 26;
            cout << L;
            generated += L; // to actually have something to use for decryption
        }
    
        {//we can use the key to regenerate the same seed:
            int seed = 0;
            for (int i = 0; i < (int)K.length(); i++)
                seed += K[i];
            srand(seed); //**** this is critical ****
        }
    
        cout << endl << "The message again is: ";
        for (int i = 0; i < (int)generated.length(); i++)
        {
            int R = rand() % K.length();
            char L = 65 + (generated[i] - 65 + (26 - (K[R] - 65)) ) % 26;//reverse shift
            cout << L;
        }
        cout << endl;
        return 0;
    }
    

    关于c++ - 用已知 key 将密文解密为明文,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34111944/

    10-10 15:01