-
Notifications
You must be signed in to change notification settings - Fork 7
/
ipcrypt.c
109 lines (95 loc) · 2.39 KB
/
ipcrypt.c
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#include "ipcrypt.h"
#define ROTL(X, R) (X) = (unsigned char) ((X) << (R)) | ((X) >> (8 - (R)))
static void
arx_fwd(unsigned char state[4])
{
state[0] += state[1];
state[2] += state[3];
ROTL(state[1], 2);
ROTL(state[3], 5);
state[1] ^= state[0];
state[3] ^= state[2];
ROTL(state[0], 4);
state[0] += state[3];
state[2] += state[1];
ROTL(state[1], 3);
ROTL(state[3], 7);
state[1] ^= state[2];
state[3] ^= state[0];
ROTL(state[2], 4);
}
static void
arx_bwd(unsigned char state[4])
{
ROTL(state[2], 4);
state[1] ^= state[2];
state[3] ^= state[0];
ROTL(state[1], 5);
ROTL(state[3], 1);
state[0] -= state[3];
state[2] -= state[1];
ROTL(state[0], 4);
state[1] ^= state[0];
state[3] ^= state[2];
ROTL(state[1], 6);
ROTL(state[3], 3);
state[0] -= state[1];
state[2] -= state[3];
}
static inline void
xor4(unsigned char *out, const unsigned char *x, const unsigned char *y)
{
out[0] = x[0] ^ y[0];
out[1] = x[1] ^ y[1];
out[2] = x[2] ^ y[2];
out[3] = x[3] ^ y[3];
}
int
ipcrypt_encrypt(unsigned char out[IPCRYPT_BYTES],
const unsigned char in[IPCRYPT_BYTES],
const unsigned char key[IPCRYPT_KEYBYTES])
{
unsigned char state[4];
int i;
xor4(state, in, key);
arx_fwd(state);
xor4(state, state, key + 4);
arx_fwd(state);
xor4(state, state, key + 8);
arx_fwd(state);
xor4(state, state, key + 12);
arx_fwd(state);
xor4(state, state, key + 4);
arx_fwd(state);
xor4(state, state, key + 8);
arx_fwd(state);
xor4(out, state, key + 12);
return 0;
}
int
ipcrypt_decrypt(unsigned char out[IPCRYPT_BYTES],
const unsigned char in[IPCRYPT_BYTES],
const unsigned char key[IPCRYPT_KEYBYTES])
{
unsigned char state[4];
xor4(state, in, key + 12);
arx_bwd(state);
xor4(state, state, key + 8);
arx_bwd(state);
xor4(state, state, key + 4);
arx_bwd(state);
xor4(out, state, key);
return 0;
}
int main(void)
{
unsigned char out[4];
const unsigned char in[4] = {1,2,3,4};
const char *key = "some 16-byte key";
const char *key2 = "some 16-byte kex";
ipcrypt_encrypt(out, in, key);
printf("%d %d %d %d\n", out[0], out[1], out[2], out[3]);
ipcrypt_encrypt(out, in, key2);
printf("%d %d %d %d\n", out[0], out[1], out[2], out[3]);
return 0;
}