Here is a small encryption program I wrote after hearing a podcast mentioning XOR encryption. Thought it could be fun for others and maybe spark some ideas for your own projects.
#include <stdio.h>
#include <unistd.h>
#include <stdbool.h>
#include <string.h>
/**
* An XOR encryption tool
*
* Usage: xor [-k key] [file or stdin]
*/
static void
xor_operate(const char *str, int strLen, const char *key)
{
static int keyIndex = 0;
int keyLen = strlen(key);
for (size_t i = 0; i < strLen; ++i) {
char ch = str[i] ^ key[keyIndex++];
printf("%c", ch);
if (keyIndex >= keyLen)
keyIndex = 0;
}
}
int
main(int argc, char* argv[])
{
int opt;
const char *key = "defaultkey";
while ((opt = getopt(argc, argv, "k:")) != -1) {
switch (opt) {
case 'k':
key = optarg;
break;
default:
break;
}
}
fprintf(stderr, "Key: %s\n", key);
FILE *in = fopen(argv[optind], "r");
if (in == NULL)
in = stdin;
char buffer[1024];
unsigned int i = 0;
char ch;
while ((ch = fgetc(in)) != -1) {
buffer[i++] = ch;
if (i >= 1024) {
xor_operate(buffer, i, key);
i = 0;
}
}
xor_operate(buffer, i, key);
return 0;
}