/* Xors the input with a hex key. * Author: Peter Wu * Date: 2013-10-05 */ #include #include #include #include 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; }