Search code examples
cwindowsencryptionxor

Simple XOR encryption giving unexpected results


...
char text[256];
fgets(text, 255, stdin);
xorEncrypt(text, 'a');
...

void xorEncrypt(char *string, char key)
    {

    int i, string_length = strlen(string);

    for(i=0; i<string_length; i++)
    {
        string[i]=string[i] ^ key;
    }
    printf("%s", string);
}

//user enters "test"
//result is: §♦↕§k (correct)
//user enters "abcdefg"
//result is empty
//user enters "testbca"
//result is "§♦↕§♥☻" (incorrect) and there is a beep sound    

When I use some chars like 'a', 'b', 'c' as a key, it gives either an empty result or some random signs, but using other letters like 'A', 'I'..., works normally and I can decrypt it.


Solution

  • The code seems fine. Probably you want to print the resulting string, but the XOR may have turned parts of it into non-printable characters. Note also that there may now be null characters in the string (e.g. 'a ^ 'a' = 0) so the end is not determined anymore by a terminating null character.