added byte wise xxtea encryption up to 32bytes

This commit is contained in:
schneider 2011-07-14 02:16:57 +02:00
parent f24b88f84b
commit 3ba6d6ef2f
2 changed files with 92 additions and 4 deletions

View File

@ -12,8 +12,90 @@
#define DELTA 0x9e3779b9
#define MX (((z>>5^y<<2) + (y>>3^z<<4)) ^ ((sum^y) + (k[(p&3)^e] ^ z)))
#include "xxtea.h"
void xxtea_encode(uint32_t *v, int n, uint32_t const k[4]) {
uint32_t charp2uint32(uint8_t *data, uint8_t bytes)
{
uint32_t r = 0;
if( bytes ){
r |= *data++;
}
if( bytes > 1){
r<<=8;
r |= *data++;
}
if( bytes > 2){
r<<=8;
r |= *data++;
}
if( bytes > 3){
r<<=8;
r |= *data++;
}
return r;
}
void charp2uint32p(uint8_t* data, uint8_t n, uint32_t *v)
{
int i,j=0;
int fullwords = n/4;
for(i=0; i<fullwords*4; i+=4){
v[j++] = charp2uint32(data+i,4);
}
uint8_t extrabytes = n - i;
v[j] = charp2uint32(data+i,extrabytes);
}
void uint322charp(uint32_t data, uint8_t *buf, uint8_t bytes)
{
if( bytes ){
buf[0] = data>>24;
if( bytes > 1)
buf[1] = (data>>16)&0xFF;
if( bytes > 2)
buf[2] = (data>>8)&0xFF;
if( bytes > 3)
buf[3] = (data>>0)&0xFF;
}
void uint32p2charp(uint8_t* data, uint8_t n, uint32_t *v)
{
int i;
int fullwords = n/4;
for(i=0; i<fullwords; i++){
uint322charp(v[i],data+i*4,4);
}
uint8_t extrabytes = n - fullwords*4;
uint322charp(v[i],data+i*4,extrabytes);
}
void xxtea_encode(uint8_t *data, int n, uint32_t const k[4])
{
uint32_t v[8]; //maximum 32 bytes
int words = (n+3)/4;
if( words > 8 )
return;
charp2uint32p(data, n, v);
xxtea_encode_words(v, words, k);
uint32p2charp(data, n, v);
}
void xxtea_decode(uint8_t *data, int n, uint32_t const k[4])
{
uint32_t v[8]; //maximum 32 bytes
int words = (n+3)/4;
if( words > 8 )
return;
charp2uint32p(data, n, v);
xxtea_decode_words(v, words, k);
uint32p2charp(data, n, v);
}
void xxtea_encode_words(uint32_t *v, int n, uint32_t const k[4])
{
uint32_t y, z, sum;
unsigned p, rounds, e;
rounds = 6 + 52/n;
@ -31,7 +113,7 @@ void xxtea_encode(uint32_t *v, int n, uint32_t const k[4]) {
} while (--rounds);
}
void xxtea_decode(uint32_t *v, int n, uint32_t const k[4]) {
void xxtea_decode_words(uint32_t *v, int n, uint32_t const k[4]) {
uint32_t y, z, sum;
unsigned p, rounds, e;

View File

@ -1,8 +1,14 @@
#ifndef _XXTEA_H_
#define _XXTEA_H_
void xxtea_encode(uint32_t *v, int n, uint32_t const k[4]);
void xxtea_decode(uint32_t *v, int n, uint32_t const k[4]);
uint32_t charp2uint32(uint8_t *data, uint8_t bytes);
void charp2uint32p(uint8_t* data, uint8_t n, uint32_t *v);
void uint322charp(uint32_t data, uint8_t *buf, uint8_t bytes);
void uint32p2charp(uint8_t* data, uint8_t n, uint32_t *v);
void xxtea_encode(uint8_t *data, int n, uint32_t const k[4]);
void xxtea_decode(uint8_t *v, int n, uint32_t const k[4]);
void xxtea_encode_words(uint32_t *v, int n, uint32_t const k[4]);
void xxtea_decode_words(uint32_t *v, int n, uint32_t const k[4]);
#endif