I am trying to xor encrypt and decrypt text using a user chosen key. The encryption step seemingly works fine but when i try to decrypt it back into plain text i get obfuscated text sometimes and other times it is readable.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
getline (cin, text);
getline(cin, key);
for (int n = 0; key[n] != '\0'; ++n) //encryption
{
for (int i = 0; text[i] != '\0'; ++i)
{
text[i] ^= key[n];
}
}
for (int n = 0; key[n] != '\0'; ++n) //"attempted" decryption
{
for (int i = 0; text[i] != '\0'; ++i)
{
text[i] ^= key[n];
}
}
For anyone that comes across this with the same problem I had here is the solution.
Determine the string length of the text and key strings BEFORE you mess around with the encryption and decryption. Otherwise when xoring the strings you may accidently produce a null terminator '\0' and this will make the loop think you are done encrypting or decrypting when you arent.
You figured out the error that some times it may get 0 when xoring. As far as your program, may I ask why you have a set of keys but you use all of the keys on each letter instead of a sequence of them on the words?
What I mean is this
Key: apple
sentence: hello world
new key: appleapplea <-- same length as the sentence
I guess the reason I didn't do that way is because I am receiving keys from the user which wouldn't necessarily match the number of text characters like in the example above.
Man you really made me rethink this whole damn code now. Now that I think about it when this code evaluates its going to look a lot like this
If the key is longer than the text, you'll just end up not using part of the key (but still, at the same time, it'll be basically impossible to break if your key is good enough and you never use it more than once: http://en.wikipedia.org/wiki/One-time_pad ).
If the text is longer than the key (most common scenario), we loop back through the key again:
Text: Hello world
Key : appleapplea
You can use the modulus operator (%) to help with "looping" back through the key.