Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
289 views
in Technique[技术] by (71.8m points)

c++ - Very long string input to xor encryption program

Description:
I am trying to write a simple program for fun that will read in a phrase then xor encrypt it then output the encrypted phrase to the terminal window. See code below for more info.

code:
#include #include using namespace std;

int main ()
{
string mystr;
cout << "What's the phrase to be Encrypted? ";

char key[11]="ABCDEFGHIJK";  //The Encryption Key, for now its generic
getline(cin, mystr);

string result;

for (int i=0; i<10; i++) {
    result.push_back(mystr[i] ^ key[i]);
    cout << result[i];
}
cout << "
";
return 0;
}

Results:
The code above works however When I input a very long string it only encrypts the first 10 characters (I think). I would like to be able to input a large string encrypt it with the 11 bit key then output it to the terminal. How do I do this?

Also:
I have asked a question that is a pre-cursor to this question located here: String input xor encryption program

help:
If you have any idea how to fix this could you please give an example of either what Im missing or what I need with explanation.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You're only looping over 10 characters as defined by your for loop for (int i=0; i<10; i++). You want to loop over your entire string length and then XOR with your key mod 11.

for (int i=0; i<mystr.size(); i++) {
    result.push_back(mystr[i] ^ key[i%11]);
    cout << result[i];
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...