维尔南密码

Vernam cipher code

本文关键字:密码      更新时间:2023-10-16

我正试图编写代码来实现c++中的vernam密码,但我的代码不运行。我不知道问题出在哪里。代码也会获得0,1和密钥中的消息,然后实现它们的异或以创建密文和相同的解密方法,当我运行它时,它会给我一个警告并停止运行。

#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);
}

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++。