diff options
author | Peter Wu <lekensteyn@gmail.com> | 2013-10-05 11:46:42 +0200 |
---|---|---|
committer | Peter Wu <lekensteyn@gmail.com> | 2013-10-05 11:46:42 +0200 |
commit | 736cc9c6e9e872a4a8689ff02d1b5dd4d920b98b (patch) | |
tree | d884edea72354a835dbfb0a0fe1d08e45b3270e4 | |
parent | d4e60b0737b1bc28705561321d1b851fa2f46e2a (diff) | |
download | c-files-736cc9c6e9e872a4a8689ff02d1b5dd4d920b98b.tar.gz |
xor: xor the input with a hex key
-rw-r--r-- | xor.c | 75 |
1 files changed, 75 insertions, 0 deletions
@@ -0,0 +1,75 @@ +/* Xors the input with a hex key. + * Author: Peter Wu <lekensteyn@gmail.com> + * Date: 2013-10-05 + */ +#include <stdio.h> +#include <unistd.h> +#include <string.h> +#include <stdlib.h> + +static inline int hex_to_char(unsigned char c1, unsigned char c2, unsigned char *dst) { + const char str[3] = { c1, c2, '\0' }; + char *end; + + *dst = strtoul(str, &end, 16); + if (*end != '\0') { + fprintf(stderr, "Not a hex octet %s\n", str); + return 1; + } + + return 0; +} + +size_t parse_hex(const char *str, unsigned char **key) { + size_t len = strlen(str); + size_t i; + + if (len == 0) { + fputs("The key must be non-empty\n", stderr); + return 0; + } + if (len % 2 != 0) { + fputs("Key length must be a multiple of 2\n", stderr); + return 0; + } + + *key = malloc(len / 2); + if (!*key) { + abort(); + } + + for (i = 0; i < len / 2; i += 2) { + if (hex_to_char(str[i], str[i + 1], &(*key)[i / 2])) { + goto fail; + } + } + + return len / 2; +fail: + free(*key); + return 0; +} + +int main(int argc, char **argv) { + unsigned char *key; + int c; + size_t key_len, key_i; + if (argc < 2) { + fputs("Usage: xor hexkey\n", stderr); + return 1; + } + + key_len = parse_hex(argv[1], &key); + if (key_len == 0) { + return 1; + } + + while ((c = getchar()) != EOF) { + putchar(((unsigned char) c) ^ key[key_i]); + key_i = (key_i + 1) % key_len; + } + + free(key); + + return 0; +} |