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;
对不起,代码乱。无论如何,所以这是我做了这么远:将密文解密为已知密钥的明文
- 用户将消息和密钥
- 用户得到密文
但现在我居然坚持了,我希望解密的事实使用正确密钥的密文。基本上,我想把密文返回给明文。我自己努力做到这一点,方法在'The message again is:'中列出,但它给了我一个错误的结果。
我在这里做错了什么?
我不得不说,在解密阶段,我没有使用任何随机生成的数字,因为我将它们存储在数组中以避免与srand()混淆。反向移位方法工作得很好。 – Hakam
你也可以在没有随机数的情况下做到这一点,然后你的代码与“Vigenere”密码非常相似。 –