PageRenderTime 34ms CodeModel.GetById 15ms app.highlight 15ms RepoModel.GetById 2ms app.codeStats 0ms

/libnpk/external/xxtea/xxtea.c

http://npk.googlecode.com/
C | 82 lines | 75 code | 7 blank | 0 comment | 13 complexity | 5f38bbda31d8abd511469ff7e9c7b7cd MD5 | raw file
 1#include <stddef.h>
 2
 3#define DELTA 0x9e3779b9
 4#define MX (((z>>5^y<<2) + (y>>3^z<<4)) ^ ((sum^y) + (k[(p&3)^e] ^ z)))
 5
 6#ifdef NPK_DEV
 7void xxtea_encode(int* v, int* k)
 8{
 9    unsigned int n = 2;
10    unsigned int y, z, sum;
11    unsigned int p, rounds, e;
12    rounds = 6 + 52/n;
13    sum = 0;
14    z = v[n-1];
15    do {
16        sum += DELTA;
17        e = (sum >> 2) & 3;
18        for (p=0; p<n-1; p++) {
19            y = v[p+1]; 
20            z = v[p] += MX;
21        }
22        y = v[0];
23        z = v[n-1] += MX;
24    } while (--rounds);
25}
26
27void xxtea_encode_byte(char* v, int* k, int p)
28{
29    char y[] = "XtEaNpK";
30    *v = *v^y[p]^(char)(k[p%4]%0xFF);
31}
32
33void xxtea_encode_buffer(char* in_buffer, unsigned int in_size, int* key, int cipherRemains)
34{
35    char *p;
36    unsigned int remain = in_size % 8;
37    unsigned int align_size = in_size - remain;
38    for (p = in_buffer; p < in_buffer + align_size; p += 8)
39        xxtea_encode( (int*)p, key);
40    if( remain > 0 && cipherRemains )
41        for (p = in_buffer + align_size; p < in_buffer + in_size; p += 1)
42            xxtea_encode_byte( p, key, --remain );
43}
44#endif
45
46void xxtea_decode(int* v,int* k)
47{
48    unsigned int n = 2;
49    unsigned int y, z, sum;
50    unsigned int p, rounds, e;
51    rounds = 6 + 52/n;
52    sum = rounds*DELTA;
53    y = v[0];
54    while (sum != 0) {
55        e = (sum >> 2) & 3;
56        for (p=n-1; p>0; p--) {
57            z = v[p-1];
58            y = v[p] -= MX;
59        }
60        z = v[n-1];
61        y = v[0] -= MX;
62        sum -= DELTA;
63    }
64}
65
66void xxtea_decode_byte(char* v, int* k, int p)
67{
68    char y[] = "XtEaNpK";
69    *v = *v^(char)(k[p%4]%0xFF)^y[p];
70}
71
72void xxtea_decode_buffer(char* in_buffer, unsigned int in_size, int* key, int cipherRemains)
73{
74    char *p;
75    unsigned int remain = in_size % 8;
76    unsigned int align_size = in_size - remain;
77    for (p = in_buffer; p < in_buffer + align_size; p += 8)
78        xxtea_decode( (int*)p, key);
79    if( remain > 0 && cipherRemains )
80        for (p = in_buffer + align_size; p < in_buffer + in_size; p += 1)
81            xxtea_decode_byte( p, key, --remain );
82}