微型加密算法TEA(12字节可完成加解密)

/ 0评 / 1

算法C代码:

#include <stdint.h>
void encrypt (uint32_t* v, uint32_t* k) {
    uint32_t v0=v[0], v1=v[1], sum=0, i;           /* set up */
    uint32_t delta=0x9e3779b9;                     /* a key schedule constant */
    uint32_t k0=k[0], k1=k[1], k2=k[2], k3=k[3];   /* cache key */
    for (i=0; i < 32; i++) {                       /* basic cycle start */
        sum += delta;
        v0 += ((v1<<4) + k0) ^ (v1 + sum) ^ ((v1>>5) + k1);
        v1 += ((v0<<4) + k2) ^ (v0 + sum) ^ ((v0>>5) + k3);
    }                                              /* end cycle */
    v[0]=v0; v[1]=v1;
}
void decrypt (uint32_t* v, uint32_t* k) {
    uint32_t v0=v[0], v1=v[1], sum=0xC6EF3720, i;  /* set up */
    uint32_t delta=0x9e3779b9;                     /* a key schedule constant */
    uint32_t k0=k[0], k1=k[1], k2=k[2], k3=k[3];   /* cache key */
    for (i=0; i<32; i++) {                         /* basic cycle start */
        v1 -= ((v0<<4) + k2) ^ (v0 + sum) ^ ((v0>>5) + k3);
        v0 -= ((v1<<4) + k0) ^ (v1 + sum) ^ ((v1>>5) + k1);
        sum -= delta;
    }                                              /* end cycle */
    v[0]=v0; v[1]=v1;
}

v就是原文或者密文,k是密码,0x9e3779b9是黄金数字,不要改.

  1. 0x9e3779b9 ⊕ 0xffffffff + 0x00000001 = 0x61C88647 = 1640531527 in decimal
  2. ~0x9e3779b9 + 0x00000001 = 0x61C88647 = 1640531527 in decimal
  3. 10011110001101110111100110111001 ⊕ 11111111111111111111111111111111 + 00000000000000000000000000000001 = 01100001110010001000011001000111 = 1640531527 in decimal

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注