gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:46:24 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com