Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

simple XOR algorithm

Although I've used C++ a lot, I'm struggling with the C differences (mainly in strings).

Could you please show me a simple single function that encrypts a message with a key using XOR comparison.

Thank-you

EDIT: Both the key and the message are char*

like image 591
Will03uk Avatar asked May 20 '26 15:05

Will03uk


2 Answers

OK, I hacked around for a minute and came up with this (only vaguely tested):

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char * xorencrypt(char * message, char * key) {
    size_t messagelen = strlen(message);
    size_t keylen = strlen(key);

    char * encrypted = malloc(messagelen+1);

    int i;
    for(i = 0; i < messagelen; i++) {
        encrypted[i] = message[i] ^ key[i % keylen];
    }
    encrypted[messagelen] = '\0';

    return encrypted;
}

int main(int argc, char * argv[]) {
    char * message = "test message";
    char * key = "abc";

    char * encrypted = xorencrypt(message, key);
    printf("%s\n", encrypted);
    free(encrypted);

    return 0;
}

Note that the function xorencrypt allocates and returns a new string, so it's the caller's responsibility to free it when done.

like image 129
Tim Avatar answered May 23 '26 21:05

Tim


C is very close to Assembler, so this example is short:

while (*string)
    *string++ ^= key;

assuming char *string; and char key.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!