# TEA

TEA算法全称微型加密算法(Tiny Encryption Algorithm)，先贴一下参考代码

#define uint unsigned int
void encrypt(uint *v, uint *key)
{
uint l = v[0], r = v[1], sum = 0, delta = 0x9e3779b9;
for (int i = 1; i <= 32; ++i)
{
sum += delta;
l += ((r << 4) + key[0]) ^ (r + sum) ^ ((r >> 5) + key[1]);
r += ((l << 4) + key[2]) ^ (l + sum) ^ ((l >> 5) + key[3]);
}
v[0] = l, v[1] = r;
}
void decrypt(uint *v, uint *key)
{
uint l = v[0], r = v[1], sum = 0, delta = 0x9e3779b9;
sum = delta * 32;
for (int i = 1; i <= 32; ++i)
{
r -= ((l << 4) + key[2]) ^ (l + sum) ^ ((l >> 5) + key[3]);
l -= ((r << 4) + key[0]) ^ (r + sum) ^ ((r >> 5) + key[1]);
sum -= delta;
}
v[0] = l, v[1] = r;
}


# XTEA

XTEA是TEA算法的加强版，他增加了密钥的数量，位运算的操作也有所增加，还有一个差别是把r的变化结果和l的变化结果进行了交替赋值

#define uint unsigned int
void encrypt(uint *v, uint *key)
{
uint l = v[0], r = v[1], sum = 0, delta = 0x9e3779b9;
for (int i = 1; i <= 32; ++i)
{
l += (((r << 4) ^ (r >> 5)) + r) ^ (sum + key[sum & 3]);
sum += delta;
r += (((l << 4) ^ (l >> 5)) + l) ^ (sum + key[(sum >> 11) & 3]);
}
v[0] = l;
v[1] = r;
}

void decrypt(uint *v, uint *key)
{
uint l = v[0], r = v[1], sum = 0, delta = 0x9e3779b9;
sum = delta * 32;
for (int i = 1; i <= 32; ++i)
{
r -= (((l << 4) ^ (l >> 5)) + l) ^ (sum + key[(sum >> 11) & 3]);
sum -= delta;
l -= (((r << 4) ^ (r >> 5)) + r) ^ (sum + key[sum & 3]);
}
v[0] = l;
v[1] = r;
}


# XXTEA

#include <cstdio>
#define uint unsigned int
#define MX (((z >> 5 ^ y << 2) + (y >> 3 ^ z << 4)) ^ ((sum ^ y) + (k[(i & 3) ^ e] ^ z)))
void xxtea(uint *v, int n, uint *k)
{
uint y, z, sum, i, t, e, delta = 0x9e3779b9;;
if (n > 1) // encrypt
{
t = 6 + 52 / n, sum = 0, z = v[n - 1];
while (t--)
{
sum += delta, e = (sum >> 2) & 3;
for (i = 0; i < n - 1; ++i)
{
y = v[i + 1];
z = v[i] += MX;
}
y = v[0];
z = v[n - 1] += MX;
}
}
else if (n < -1) // decrypt
{
n = -n, t = 6 + 52 / n, sum = t * delta, y = v[0];
while (t--)
{
e = (sum >> 2) & 3;
for (i = n - 1; i > 0; --i)
{
z = v[i - 1];
y = v[i] -= MX;
}
z = v[n - 1];
y = v[0] -= MX;
sum -= delta;
}
}
}
int main()
{
uint v[2]= {1,2}, k[4]= {2,2,3,4};
int n = 2; // abs(n) = strlen(v)
printf("data: %u %u\n",v[0],v[1]);
xxtea(v, n, k);
printf("encrypt:%u %u\n",v[0],v[1]);
xxtea(v, -n, k);
printf("decrypt: %u %u\n",v[0],v[1]);
return 0;
}

posted @ 2021-11-29 19:53  iPlayForSG  阅读(162)  评论(0编辑  收藏  举报