2015-10-15 26 views
-1

我正在尝试编写代码来实现C++中的vernam密码,但是我的代码无法运行。我不知道问题是什么。代码将得到零,一个和密钥的消息,然后实现它们的XOR以创建密文和解密方法,当我运行它时,会发出警告并停止运行。Vernam密码

#include<iostream> 
#include<string> 
using namespace std; 
void encrypt(string msg, string key) 
{ 
    while (msg.length() > key.length()) 
    { 
     key += key; 
    } 
    string encrypt_Text = ""; 
    for (size_t i = 0; i <= msg.length(); i++) 
    { 

     encrypt_Text += msg[i]^key[i]; 
    } 
    cout << "the cipher text is:" << encrypt_Text << endl; 

} 

void decrypt(string cipher, string key) 
{ 
    while (cipher.length() > key.length()) 
    { 
     key += key; 
    } 
    string decrypt_Text = ""; 
    for (int i = 0; i <= cipher.length(); i++) 
    { 

     decrypt_Text += cipher[i]^key[i]; 
    } 
    cout << "the messege is:" << decrypt_Text << endl; 
} 

void main() 
{ 
    string msg, key; 
    cout << "enter your messege in boolean : " << endl; 
    cin >> msg; 
    cout << "enter your key in boolean : " << endl; 
    cin >> key; 
    encrypt(msg, key); 
} 
+0

我很难理解你的问题是什么。你能否用错误信息的确切文本或示例输入和输出来显示问题? – CodeMouse92

+1

这听起来像你可能需要学习如何使用调试器来遍历代码。使用一个好的调试器,您可以逐行执行您的程序,并查看它与您期望的偏离的位置。如果你打算做任何编程,这是一个重要的工具。进一步阅读:** [如何调试小程序](http://ericlippert.com/2014/03/05/how-to-debug-small-programs/)** – NathanOliver

+0

它是警告错误,不运行 –

回答

0

encrypt()功能,试试这个:

encrypt_Text+=((msg[i]-'0')^(key[i]-'0')+'0'); 

否则,你正在使用的字符的ASCII码。此外,修改循环,使其使用<,而不是<=

for(size_t i=0; i<msg.length(); i++) 
//    ^smaller, not smaller or equal 

和修改main()返回类型int,这是C++。

+0

谢谢非常,这是工作。 –

+0

但请,什么味精[我] - '0'的意思是? –

+0

'msg [i]'是一个'char',例如'A'表示为'65',即它的[ASCII码](http://www.asciitable.com/)。现在,数字以ASCII码“48”开始为“0”,开始于“57”为“9”,连续。所以当你写例如'''''''''你得到* number *'1',这是你想要的,而不是''1''的ASCII码,它是'49'。请注意,C++标准没有强制使用ASCII,其中提到的技巧是可行的,因为代码是连续的。如果你想超级超级安全,可以使用'atoi'来代替。 – vsoftco