1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
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;
}
|