2011-07-13 23:27:54 +00:00
|
|
|
/* simple XXTEA en/decrypt utility
|
|
|
|
*
|
|
|
|
* BSD Licence
|
|
|
|
*
|
|
|
|
* btea function is from
|
|
|
|
* <https://secure.wikimedia.org/wikipedia/en/wiki/XXTEA#Reference_code>
|
|
|
|
*
|
|
|
|
* (c) by Sec <sec@42.org> 6/2011
|
|
|
|
*/
|
|
|
|
|
|
|
|
#include <stdint.h>
|
2011-07-18 08:31:20 +00:00
|
|
|
#include "xxtea.h"
|
|
|
|
|
2011-07-18 19:42:17 +00:00
|
|
|
#ifdef SAFE
|
2011-07-18 08:31:20 +00:00
|
|
|
uint32_t htonl(uint32_t v)
|
|
|
|
{
|
2011-07-18 16:24:34 +00:00
|
|
|
uint32_t r=0;
|
2011-07-18 08:31:20 +00:00
|
|
|
r |= (v>> 0)&0xFF; r<<=8;
|
|
|
|
r |= (v>> 8)&0xFF; r<<=8;
|
|
|
|
r |= (v>>16)&0xFF; r<<=8;
|
|
|
|
r |= (v>>24)&0xFF;
|
|
|
|
return r;
|
|
|
|
}
|
2011-07-18 19:42:17 +00:00
|
|
|
#else
|
|
|
|
uint32_t htonl(uint32_t v){
|
|
|
|
__asm("rev %[value], %[value];" \
|
|
|
|
: [value] "+r" (v) : );
|
|
|
|
return v;
|
|
|
|
};
|
|
|
|
#endif
|
|
|
|
|
2011-07-18 08:31:20 +00:00
|
|
|
|
|
|
|
void htonlp(uint32_t *v, uint8_t n)
|
|
|
|
{
|
|
|
|
while(n--){
|
|
|
|
v[n] = htonl(v[n]);
|
|
|
|
}
|
|
|
|
}
|
2011-07-13 23:27:54 +00:00
|
|
|
|
|
|
|
#define DELTA 0x9e3779b9
|
|
|
|
#define MX (((z>>5^y<<2) + (y>>3^z<<4)) ^ ((sum^y) + (k[(p&3)^e] ^ z)))
|
|
|
|
|
2011-07-14 00:16:57 +00:00
|
|
|
void xxtea_encode_words(uint32_t *v, int n, uint32_t const k[4])
|
|
|
|
{
|
2011-07-16 17:12:35 +00:00
|
|
|
if(k[0] == 0 && k[1] == 0 && k[2] == 0 && k[3] == 0) return;
|
2011-07-13 23:27:54 +00:00
|
|
|
uint32_t y, z, sum;
|
|
|
|
unsigned p, rounds, e;
|
2011-07-18 08:31:20 +00:00
|
|
|
|
|
|
|
htonlp(v ,n);
|
2011-07-13 23:27:54 +00:00
|
|
|
rounds = 6 + 52/n;
|
|
|
|
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);
|
2011-07-18 08:31:20 +00:00
|
|
|
htonlp(v ,n);
|
2011-07-13 23:27:54 +00:00
|
|
|
}
|
|
|
|
|
2011-07-14 00:24:33 +00:00
|
|
|
void xxtea_decode_words(uint32_t *v, int n, uint32_t const k[4])
|
|
|
|
{
|
2011-07-16 17:12:35 +00:00
|
|
|
if(k[0] == 0 && k[1] == 0 && k[2] == 0 && k[3] == 0) return;
|
2011-07-13 23:27:54 +00:00
|
|
|
uint32_t y, z, sum;
|
|
|
|
unsigned p, rounds, e;
|
2011-07-18 08:31:20 +00:00
|
|
|
htonlp(v ,n);
|
2011-07-13 23:27:54 +00:00
|
|
|
|
|
|
|
rounds = 6 + 52/n;
|
|
|
|
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;
|
|
|
|
} while ((sum -= DELTA) != 0);
|
2011-07-18 08:31:20 +00:00
|
|
|
htonlp(v ,n);
|
2011-07-13 23:27:54 +00:00
|
|
|
}
|
|
|
|
|