-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathxxtea.c
446 lines (351 loc) · 11.6 KB
/
xxtea.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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
/*
* Copyright (c) 2014-2020, Yue Du
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <Python.h>
#include <ctype.h>
#include <stdio.h>
#define VERSION "3.3.0"
#if PY_MAJOR_VERSION >= 3
#define PyString_FromStringAndSize PyBytes_FromStringAndSize
#define PyString_AS_STRING PyBytes_AsString
#endif
#if PY_VERSION_HEX < 0x030900A4 && !defined(Py_SET_SIZE)
#if defined(_MSC_VER) && !defined(inline)
#define inline __inline /* required for py2.x support on windows */
#endif
static inline void _Py_SET_SIZE(PyVarObject *ob, Py_ssize_t size)
{ ob->ob_size = size; }
#define Py_SET_SIZE(ob, size) _Py_SET_SIZE((PyVarObject*)(ob), size)
#endif
#define XFREE(o) do { if ((o) == NULL) ; else free(o); } while (0)
#define DELTA 0x9e3779b9
#define MX (((z>>5^y<<2) + (y>>3^z<<4)) ^ ((sum^y) + (key[(p&3)^e] ^ z)))
static PyObject *module, *binascii;
static void btea(unsigned int *v, int n, unsigned int const key[4], unsigned int rounds)
{
unsigned int y, z, sum;
unsigned p, e;
if (n > 1) { /* Coding Part */
rounds = rounds == 0 ? 6 + 52 / n: rounds;
sum = 0;
z = v[n - 1];
do {
sum += DELTA;
e = (sum >> 2) & 3;
for (p = 0; p < n - 1; p++) {
y = v[p + 1];
z = v[p] += MX;
}
y = v[0];
z = v[n - 1] += MX;
}
while (--rounds);
}
else if (n < -1) { /* Decoding Part */
n = -n;
rounds = rounds == 0 ? 6 + 52 / n: rounds;
sum = rounds * DELTA;
y = v[0];
do {
e = (sum >> 2) & 3;
for (p = n - 1; p > 0; p--) {
z = v[p - 1];
y = v[p] -= MX;
}
z = v[n - 1];
y = v[0] -= MX;
sum -= DELTA;
}
while (--rounds);
}
}
static int bytes2longs(const char *in, int inlen, unsigned int *out, int padding)
{
int i, pad;
const unsigned char *s;
s = (const unsigned char *)in;
/* (i & 3) << 3 -> [0, 8, 16, 24] */
for (i = 0; i < inlen; i++) {
out[i >> 2] |= s[i] << ((i & 3) << 3);
}
/* PKCS#7 padding */
if (padding) {
pad = 4 - (inlen & 3);
/* make sure lenght of out >= 2 */
pad = (inlen < 4) ? pad + 4 : pad;
for (i = inlen; i < inlen + pad; i++) {
out[i >> 2] |= pad << ((i & 3) << 3);
}
}
/* Divided by 4, and then rounded up (ceil) to an integer.
* Which is the number of how many longs we've got.
*/
return ((i - 1) >> 2) + 1;
}
static int longs2bytes(unsigned int *in, int inlen, char *out, int padding)
{
int i, outlen, pad;
unsigned char *s;
s = (unsigned char *)out;
for (i = 0; i < inlen; i++) {
s[4 * i] = in[i] & 0xFF;
s[4 * i + 1] = (in[i] >> 8) & 0xFF;
s[4 * i + 2] = (in[i] >> 16) & 0xFF;
s[4 * i + 3] = (in[i] >> 24) & 0xFF;
}
outlen = inlen * 4;
/* PKCS#7 unpadding */
if (padding) {
pad = s[outlen - 1];
outlen -= pad;
if (pad < 1 || pad > 8) {
/* invalid padding */
return -1;
}
if (outlen < 0) {
return -2;
}
for (i = outlen; i < inlen * 4; i++) {
if (s[i] != pad) {
return -3;
}
}
}
s[outlen] = '\0';
/* How many bytes we've got */
return outlen;
}
/*****************************************************************************
* Module Functions ***********************************************************
****************************************************************************/
static char *keywords[] = {"data", "key", "padding", "rounds", NULL};
PyDoc_STRVAR(
xxtea_encrypt_doc,
"encrypt (data, key, padding=True, rounds=0)\n\n"
"Encrypt `data` with a 16-byte `key`, return binary bytes.");
static PyObject *xxtea_encrypt(PyObject *self, PyObject *args, PyObject *kwargs)
{
int alen, dlen, klen, padding;
PyObject *retval;
char *retbuf;
unsigned int *d, k[4], rounds;
Py_buffer data, key;
d = NULL;
retval = NULL;
k[0] = k[1] = k[2] = k[3] = 0;
padding = 1;
rounds = 0;
data.buf = data.obj = key.buf = key.obj = NULL;
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s*s*|iI", keywords, &data, &key, &padding, &rounds)) {
return NULL;
}
padding = padding != 0 ? 1 : 0;
dlen = data.len;
klen = key.len;
if (klen != 16) {
PyErr_SetString(PyExc_ValueError, "Need a 16-byte key.");
goto cleanup;
}
if (!padding && (dlen < 8 || (dlen & 3) != 0)) {
PyErr_SetString(PyExc_ValueError, "Data length must be a multiple of 4 bytes and must not be less than 8 bytes");
goto cleanup;
}
alen = dlen < 4 ? 2 : (dlen >> 2) + padding;
d = (unsigned int *)calloc(alen, sizeof(unsigned int));
if (d == NULL) {
PyErr_NoMemory();
goto cleanup;
}
Py_BEGIN_ALLOW_THREADS
bytes2longs(data.buf, dlen, d, padding);
bytes2longs(key.buf, klen, k, 0);
btea(d, alen, k, rounds);
Py_END_ALLOW_THREADS
PyBuffer_Release(&data);
PyBuffer_Release(&key);
retval = PyString_FromStringAndSize(NULL, (alen << 2));
if (!retval) {
goto cleanup;
}
retbuf = PyString_AS_STRING(retval);
longs2bytes(d, alen, retbuf, 0);
free(d);
return retval;
cleanup:
XFREE(d);
Py_XDECREF(retval);
PyBuffer_Release(&data);
PyBuffer_Release(&key);
return NULL;
}
PyDoc_STRVAR(
xxtea_encrypt_hex_doc,
"encrypt_hex (data, key, padding=True, rounds=0)\n\n"
"Encrypt `data` with a 16-byte `key`, return hex encoded bytes.");
static PyObject *xxtea_encrypt_hex(PyObject *self, PyObject *args, PyObject *kwargs)
{
PyObject *retval, *tmp;
retval = tmp = NULL;
if (!(tmp = xxtea_encrypt(self, args, kwargs))) {
return NULL;
}
retval = PyObject_CallMethod(binascii, "hexlify", "(O)", tmp, NULL);
Py_DECREF(tmp);
return retval;
}
PyDoc_STRVAR(
xxtea_decrypt_doc,
"decrypt (data, key, padding=True, rounds=0)\n\n"
"Decrypt `data` with a 16-byte `key`, return original bytes.");
static PyObject *xxtea_decrypt(PyObject *self, PyObject *args, PyObject *kwargs)
{
int alen, dlen, klen, rc, padding;
PyObject *retval;
char *retbuf;
unsigned int *d, k[4], rounds;
Py_buffer data, key;
d = NULL;
retval = NULL;
k[0] = k[1] = k[2] = k[3] = 0;
padding = 1;
rounds = 0;
data.buf = data.obj = key.buf = key.obj = NULL;
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s*s*|iI", keywords, &data, &key, &padding, &rounds)) {
return NULL;
}
padding = padding != 0 ? 1 : 0;
dlen = data.len;
klen = key.len;
if (klen != 16) {
PyErr_SetString(PyExc_ValueError, "Need a 16-byte key.");
goto cleanup;
}
if (!padding && (dlen < 8 || dlen & 3)) {
PyErr_SetString(PyExc_ValueError, "Data length must be a multiple of 4 bytes and must not be less than 8 bytes");
goto cleanup;
}
retval = PyString_FromStringAndSize(NULL, dlen);
if (!retval) {
goto cleanup;
}
retbuf = PyString_AS_STRING(retval);
/* not divided by 4, or length < 8 */
if (dlen & 3 || dlen < 8) {
PyErr_SetString(PyExc_ValueError, "Invalid data, data length is not a multiple of 4, or less than 8.");
goto cleanup;
}
alen = dlen / 4;
d = (unsigned int *)calloc(alen, sizeof(unsigned int));
if (d == NULL) {
PyErr_NoMemory();
goto cleanup;
}
Py_BEGIN_ALLOW_THREADS
bytes2longs(data.buf, dlen, d, 0);
bytes2longs(key.buf, klen, k, 0);
btea(d, -alen, k, rounds);
rc = longs2bytes(d, alen, retbuf, padding);
Py_END_ALLOW_THREADS
PyBuffer_Release(&data);
PyBuffer_Release(&key);
if (padding) {
if (rc >= 0) {
/* Remove PKCS#7 padded chars */
Py_SET_SIZE(retval, rc);
}
else {
/* Illegal PKCS#7 padding */
PyErr_SetString(PyExc_ValueError, "Invalid data, illegal PKCS#7 padding. Could be using a wrong key.");
goto cleanup;
}
}
free(d);
return retval;
cleanup:
XFREE(d);
Py_XDECREF(retval);
PyBuffer_Release(&data);
PyBuffer_Release(&key);
return NULL;
}
PyDoc_STRVAR(
xxtea_decrypt_hex_doc,
"decrypt_hex (data, key, padding = True)\n\n"
"Decrypt hex encoded `data` with a 16-byte `key`, return original bytes.");
static PyObject *xxtea_decrypt_hex(PyObject *self, PyObject *args, PyObject *kwargs)
{
PyObject *data, *key, *padding, *rounds, *retval, *tmp;
data = key = retval = tmp = NULL;
padding = Py_BuildValue("i", 1);
rounds = Py_BuildValue("I", 0);
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "SS|OO", keywords, &data, &key, &padding, &rounds)) {
goto cleanup;
}
if (!(tmp = PyObject_CallMethod(binascii, "unhexlify", "(O)", data, NULL))) {
goto cleanup;
}
retval = PyObject_CallMethod(module, "decrypt", "(OOOO)", tmp, key, padding, rounds, NULL);
Py_DECREF(tmp);
return retval;
cleanup:
Py_DECREF(padding);
Py_DECREF(rounds);
return NULL;
}
/*****************************************************************************
* Module Init ****************************************************************
****************************************************************************/
/* ref: https://docs.python.org/2/howto/cporting.html */
static PyMethodDef methods[] = {
{"encrypt", (PyCFunction)xxtea_encrypt, METH_VARARGS | METH_KEYWORDS, xxtea_encrypt_doc},
{"decrypt", (PyCFunction)xxtea_decrypt, METH_VARARGS | METH_KEYWORDS, xxtea_decrypt_doc},
{"encrypt_hex", (PyCFunction)xxtea_encrypt_hex, METH_VARARGS | METH_KEYWORDS, xxtea_encrypt_hex_doc},
{"decrypt_hex", (PyCFunction)xxtea_decrypt_hex, METH_VARARGS | METH_KEYWORDS, xxtea_decrypt_hex_doc},
{NULL, NULL, 0, NULL}
};
static struct PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT,
"xxtea",
NULL,
-1,
methods,
NULL,
NULL,
NULL,
NULL
};
PyObject *PyInit_xxtea(void)
{
module = PyModule_Create(&moduledef);
if (module == NULL) {
return NULL;
}
if (!(binascii = PyImport_ImportModule("binascii"))) {
Py_DECREF(module);
return NULL;
}
PyModule_AddStringConstant(module, "VERSION", VERSION);
return module;
}