c++ - 使用已知 key 将密文解密为明文

标签 c++ encryption

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;

对不起,乱七八糟的代码。无论如何,这是我到目前为止所做的:

  • 用户插入消息和 key
  • 用户得到一个密文

但现在我实际上坚持使用正确的 key 解密密文这一事实。基本上,我想将密文恢复为明文。我自己努力做到这一点,该方法列在“消息再次是:”下,但它给了我一个错误的结果。

我在这里做错了什么?

最佳答案

这段代码很奇怪,但它确实可以工作。前提是编码器和解码器是由同一个编译器制作的,并且可能在同一台计算机上。

您正在使用 key 为 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/

相关文章:

c++ - 程序在代码块中调试时收到信号 SIGSEGV,段错误

c++ - 使用 && 和 || 有什么区别在 do...while 循环中?

c++ - 如何在构造函数中初始化 std::unique_ptr?

c# - 从 C++ 获取复杂结构到 C#

java - 密码加密速度明显慢

php - Paypal 加密网站支付

c++ - 使用补码加密文件

c++ - 不存在合适的构造函数可从 "uint8_t *"转换为 "std::vector<uint8_t, std::allocator<uint8_t>>"

C: 用户输入字符串包括 "' "-character

c# - 如何在 C# 中解密在 Delphi 中加密的字符串