Encryption

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];
        }
    }
Last edited on
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

which would look like:
h^a
e^p
l^p
l^l
o^e
 ^a
w^p
o^p
r^l
l^e
d^a


but what you are doing is:
h^a^p^p^l^e
e^a^p^p^l^e
l^a^p^p^l^e
l^a^p^p^l^e
o^a^p^p^l^e
 ^a^p^p^l^e
w^a^p^p^l^e
o^a^p^p^l^e
r^a^p^p^l^e
l^a^p^p^l^e
d^a^p^p^l^e


*fixed tags
Last edited on
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
1
2
3
4
5
6
7
8
9
10
11
h^(some character x)
e^x
l^x
l^x
o^x
 ^x
w^x
o^x
r^x
l^x
d^x

And this doesnt seem like very good encryption
Last edited on
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.
Thanks for the help guys
Topic archived. No new replies allowed.