Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to decrypt simple XOR encryption

Tags:

c

encryption

xor

I found the following XOR encryption function on the internet:

void xor_encrypt(char *key, char *string)
{
    int i, string_length = strlen(string);
    for(i=0; i<string_length; i++)
    {
        string[i]=string[i]^key[i];
        printf("%i", string[i]);
    }
}

It works perfect, but I would like to decrypt the string also.

For example:

void xor_decrypt(char *key, char *encrypted_string)
{
    //decrypt method goes here
}

So basically after I encrypt the string, I would use the same encryption key to decrypt the previously encrypted string.

I'm pretty new to programming and I would just like to know how to decrypt the previously encrypted string. Thanks, all help is appreciated.

like image 502
user3101398 Avatar asked Dec 14 '13 03:12

user3101398


1 Answers

One of the cool things about XOR encryption is that when you apply it twice, you get back the original string – see http://en.wikipedia.org/wiki/XOR_cipher.

In your function, xor_decrypt, you take string and key and return string ^ key. If, now, you xor that with the key again, you get (string ^ key) ^ key = string ^ (key ^ key) = string ^ identity = string (by properties of XOR operator: http://en.wikipedia.org/wiki/Exclusive_or#Properties)

Thus, you can just run your function, xor_encrypt, a second time on the output of the first xor_encrypt.

like image 58
dmitrig01 Avatar answered Oct 09 '22 16:10

dmitrig01