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*
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.
C is very close to Assembler, so this example is short:
while (*string)
*string++ ^= key;
assuming char *string; and char key.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With