2015-12-05 43 views
1
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:'中列出,但它给了我一个错误的结果。

我在这里做错了什么?

回答

1

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

您正在使用密钥来生成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; 
} 
+0

我不得不说,在解密阶段,我没有使用任何随机生成的数字,因为我将它们存储在数组中以避免与srand()混淆。反向移位方法工作得很好。 – Hakam

+0

你也可以在没有随机数的情况下做到这一点,然后你的代码与“Vigenere”密码非常相似。 –

1

不完全确定,因为我没有真正编译新的解决方案,但我的猜测是因为您在解密阶段使用了新的随机数。您需要保留加密中使用的原始随机数,以使该功能可以反转。

+0

我调试它,它似乎产生的随机数序列是相等的。但是,我相信错误发生了,所以我将它存储在一个数组中,只是为了确保。 – Hakam