+ 1
How to implent XOR encryption C++ -_-
Every for loop I have attempted is either deleting my string, or my android phone cant display the new characters after encryption. It's really frustrating, as this was suppossed to be a stricly for-fun project. I need help coders this is my 3rd day of trying. #include <string> #include <iostream> using namespace std; int main(){ string message = "test"; char key = 's'; for (int i= 0; i < message.size(); i++) message[i] ^= key; cout << "\n Encrypted = " << message; return 0; }
3 Answers
0
Okay, I'll see if I can give you a play-by-play.
Every character inside the string is run through an XOR with the key, which is 's'. In binary, 's' is 01110011. So, if we run each one of these characters through the XOR encryption, the result will be:
't' XOR 's' = 01110100 XOR 01110011 = 00000111
'e' XOR 's' = 01100101 XOR 01110011 = 00010110
's' XOR 's' = 01110011 XOR 01110011 = 00000000
't' XOR 's' = 00000111 (as above)
The resulting output string, according to the ASCII table, would be:
BEL, SYN, NUL, BEL
These are actually names given to signals that are sent between computers and components within your computer. None of those signals were meant to actually be displayed on the screen, and actually trying to do so is what's giving you odd results. You can still use it to encrypt your string, but the encrypted result won't be in a printable format.
Oh, and if you want to decrypt the string, just perform another XOR operation with the encrypted string and the key.
0
Thank you so much for a thorough explanation. I appreciate your time and effort. Can I implement a way to see the encryption?
0
If you want to see the encrypted string, try adding a number to each character within it. For instance, if we add 33 to the XOR-encrypted string:
for (int i = 0; i < message.size(); i++){
message[i] ^= 's';
message[i] += 33;
}
The resulting string ought to be (7!(.
To decrypt the string:
for (int i = 0; i < message.size; i++){
message[i] -= 33;
message[i] ^= 's';
}