tea&xtea加解密函数模板(c语言)
tea和xtea的核心在v0的状态是根据v1和sum来更新的,v1的状态是根据v0和sum来更新的,ctf中经常遇到各种变种的tea xtea,可能是修改了delta,或者是更改了v0 v1更新的方式,或者是修改了更新的轮数,编写decrypt方式都大同小异,可以根据下面的模板来修改
xtea在tea的基础上,取k的时候使用k[] 这种方式动态的取key,感觉是为了使每次更新v0 v1更随机
tea的实现
void teacrypt(uint32_t* v,uint32_t* k) {
uint32_t v0 = v[0], v1 = v[1], sum = 0, i;
uint32_t delta = 0x9e3779b9;
uint32_t k0 = k[0], k1 = k[1], k2 = k[2], k3 = k[3];
for (i = 0; i < 32; i++)
{
sum += delta;
v0 += ((v1 << 4) + k0) ^ (v1 + sum) ^ ((v1 >> 5) + k1);
v1 += ((v0 << 4) + k2) ^ (v0 + sum) ^ ((v0 >> 5) + k3);
}
v[0] = v0; v[1] = v1;
}
void teadecrypto(uint32_t* v, uint32_t* k) {
uint32_t v0 = v[0], v1 = v[1], sum = 0xc6ef3720, i;
uint32_t delta = 0x9e3779b9;
uint32_t k0 = k[0], k1 = k[1], k2 = k[2], k3 = k[3];
for (i = 0; i < 32; i++)
{
v1 -= ((v0 << 4) + k2) ^ (v0 + sum) ^ ((v0 >> 5) + k3);
v0 -= ((v1 << 4) + k0) ^ (v1 + sum) ^ ((v1 >> 5) + k1);
sum -= delta;
}
v[0] = v0; v[1] = v1;
}
xtea的实现
void xteacrypt(uint32_t *v, uint32_t *k) {
uint32_t v0 = v[0], v1 = v[1];
uint32_t k0 = k[0], k1 = k[1], k2 = k[2], k3 = k[3];
int sum = 0, delta = 0x9e3779b9;
for (size_t i = 0; i < 32; i++)
{
v0 += (((v1 << 4) ^ (v1 >> 5)) + v1) ^ (sum + k[sum & 3]);
sum += delta;
v1 += (((v0 << 4) ^ (v0 >> 5)) + v0) ^ (sum + k[(sum >> 11) & 3]);
}
v[0] = v0; v[1] = v1;
}
void xteadecrypt(uint32_t* v, uint32_t* k) {
uint32_t v0 = v[0], v1 = v[1];
uint32_t k0 = k[0], k1 = k[1], k2 = k[2], k3 = k[3];
int sum = 0x9e3779b9 * 32, delta = 0x9e3779b9;
for (size_t i = 0; i < 32; i++)
{
v1 -= (((v0 << 4) ^ (v0 >> 5)) + v0) ^ (sum + k[(sum >> 11) & 3]);
sum -= delta;
v0 -= (((v1 << 4) ^ (v1 >> 5)) + v1) ^ (sum + k[sum & 3]);
}
v[0] = v0; v[1] = v1;
}