输入/输出XORD字符串的C++问题 我是C++初学者,我正在做一个XOR加密程序。当我手动将代码输入到我的程序中时,我的程序运行良好。当我试图解密一个加密的短语,而程序只返回该短语的第一个单词时,就会出现这个问题
例如: 要加密的输入字符串:hello world 关键词:q 加密字符串:V 输入要解密的字符串:V 关键词:q 输出:您好 它只给了我第一个单词,我想这与我获取输入和输出的方式有关 非常感谢你输入/输出XORD字符串的C++问题 我是C++初学者,我正在做一个XOR加密程序。当我手动将代码输入到我的程序中时,我的程序运行良好。当我试图解密一个加密的短语,而程序只返回该短语的第一个单词时,就会出现这个问题,c++,encryption,cin,getline,xor,C++,Encryption,Cin,Getline,Xor,例如: 要加密的输入字符串:hello world 关键词:q 加密字符串:V 输入要解密的字符串:V 关键词:q 输出:您好 它只给了我第一个单词,我想这与我获取输入和输出的方式有关 非常感谢你 #include <iostream> #include <stdio.h> #include <stdlib.h> #include <string> #include <fstream> using namespace std; /*E
#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);
我认为问题在于字符串XORString函数,请尝试以下方法:
//change this
newXOR += XORString[i]^(int(key+i))%255;
//to
newXOR = XORString[i];
我希望这能解决我对运算符exclusive OR不太了解的问题,但我认为这是导致字符串函数出现问题的原因如果它不起作用,请告诉我,以便我可以尝试找到另一种解决方法。^的优先级是否高于%?添加括号可以为你自己和你的读者省去很多痛苦。这可能是一个字符异或的问题。如果字符相等,您将生成一个空字符,即C/C++中表示字符串结尾的控制字符。XOR表示二进制;您应该重新处理或编码生成的二进制文件,或者使用另一种加密方案,如模块相加