Press "Enter" to skip to content

TEA算法

TEA 算法介绍

TEA(Tiny Encryption Algorithm), 一次可以加密64 bit(8 byte, 或2 int_32),使用一个128 bit(16 byte, 或4 int_32)的key。使用一个delta常数,通常为0x9E3779B9。推荐迭代轮数为64轮,最少32轮。

加密

加密过程图示(两轮)

公式表示

[latex]L’ = L + ((R << 4) + K[0]) \oplus (R + delta_i) \oplus ((R >> 5) + K[1])\\[/latex]

[latex]R’ = R + ((L’ << 4) + K[2]) \oplus (L' + delta_i) \oplus ((L' >> 5) + K[3])[/latex]

C代码实现

const int delta = 0x9E3779B9

void encrypt(int* value, int* key, int round)
{
    int l = value[0], r = value[1], sum = 0;
    for(int i = 0; i < round; ++i)
    {
        l += ((r << 4) + key[0]) ^ (r + sum) ^ ((r >> 5) + key[1]);
        sum += delta;
        r += ((l << 4) + key[2]) ^ (l + sum) ^ ((l >> 5) + key[3]);
    }
    value[0] = l, value[1] = r;
}

解密

解密过程即是加密过程的逆过程

公式表示

[latex]R’ = R + ((L’ << 4) + K[2]) \oplus (L’ + delta_i) \oplus ((L’ >> 5) + K[3])\\[/latex]

[latex]L’ = L + ((R << 4) + K[0]) \oplus (R + delta_i) \oplus ((R >> 5) + K[1])[/latex]

C语言实现

const int delta = 0x9E3779B9

void decrypt(int* value, int* key, int round)
{
    int l = value[0], r = value[1], sum = delta * round;
    for(int i = 0; i < round; ++i)
    {
        r -= ((l << 4) + key[2]) ^ (l + delta * i) ^ ((l >> 5) + key[3]);
        sum -= delta;
        l -= ((r << 4) + key[0]) ^ (r + delta * i) ^ ((r >> 5) + key[1]);
    }
    value[0] = l, value[1] = r;
}