输入/输出异或字符串的 C++ 问题



我是C 的初学者,我正在研究XOR加密程序。当我手动将代码输入程序中时,我的程序正常工作。当我尝试解密加密的短语并且程序仅返回该短语的第一个单词时,就会发生问题。

示例:输入的字符串到加密:Hello World

键:q

加密字符串:v

输入的字符串被解密:v

键:q

输出:你好

它只给了我第一个单词,我认为这与我接受输入和输出的方式有关。

非常感谢!

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <fstream>
using namespace std;
/*Encrypt/decrypt program that takes in a string and encrypts it using a single byte xor encryption. Program can also decrypt a given string with or without a key.*/
string XOR(string input, char key){
    string XORString = input;
    string newXOR = "";
    for(int i = 0; i < input.length();i++){
       newXOR += XORString[i]^(int(key+i))%255;
    }
    return newXOR;
}
int main()
{
    /*char key = 'q';
    std::cout << XOR("hello world",key);
    return 0;
   The lines above are for manual testing if needed*/
    bool b = true;
    while(b){
        int x;
        cout<<"Enter 1 for Encryption, 2 for Decryption, 3 for Decryption without key or 4 to end program."<<endl;
        cin>>x;
        if(x==1){
            string phrase1 = "";
            cout<< "Enter a phrase to encrypt: ";
            cin.ignore();
            getline(std::cin,phrase1);
            cout<<"Enter a key to encrypt with: ";
            char key1;
            cin>> key1;
            std::cout << XOR(phrase1,key1)<< endl;
       }
        else if(x==2){
            string phrase = "";
            cout<< "Enter a phrase to decrypt: ";
            cin.ignore();
            std::getline(std::cin,phrase);
            cout<<"Enter a key to decrypt with: ";
            char key2;
            cin>>key2;
            std::cout << XOR(phrase,key2)<<endl;
        }
        else if(x==3){
            char keys [] = {'!','"','#','$','%','&','(',')','*','+',',','-','.','/','0','1','2','3','4','5','6','7','8','9',':',';','<','=','>','?','@','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','[',']','^','_','`','a','b','c','d','e','f','g','h','I','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','{','|','}','~'};
            int end = 92;
            int count = 0;
            string s;
            cout<< "Enter phrase: ";
            cin>>s;
            for(int i = 0; i < 92;i++){
                count++;
                cout<<count<<" possible combination out of " << end << " using " << keys[i]<< ":"<<XOR(s,keys[i])<<endl;
            }
        }
        else if(x==4){
            cout<<"Have a nice day!";
            b = false;
        }
        else{
            cout<<"You entered an invalid number";
            break;
        }
    }
    return 0;

这可能是问题代码:

            string phrase1 = "";
            cout<< "Enter a phrase to encrypt: ";
            cin.ignore();
            getline(std::cin,phrase1);

我认为问题是您的字符串Xorsring函数尝试以下方法:

//change this
newXOR += XORString[i]^(int(key+i))%255;
//to
newXOR = XORString[i];

我希望这能解决我对操作员独家不太了解的问题,或者我认为这会导致字符串函数中的问题

最新更新