Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
480 views
in Technique[技术] by (71.8m points)

c - How to decrypt simple XOR encryption

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...