C - 无法实现微小加密算法(意外值)

时间:2015-08-14 04:32:47

标签: c algorithm encryption

对于笑话,我正在尝试实现最终将使用Arduino的Tiny Encryption Algorithm(TEA)版本。是的,我知道TEA坏了,但没关系 - 它不会被用于除了蜿蜒的好奇之外的任何东西。

输出:

加密:[DC2F C574]
解密:[698D 5E42]

代码:

#include <stdio.h>
#include <stdint.h>

uint16_t KEY[4];

void encrypt(uint16_t *v) {
  uint16_t v0=v[0], v1=v[1], sum=0, i;           // set up
  uint16_t delta=0x9e37;                         // a key schedule constant
  for (i=0; i < 32; i++) {                       // basic cycle start
    sum += delta;
    v0 += ((v1<<4) + KEY[0]) ^ (v1 + sum) ^ ((v1>>5) + KEY[1]);
    v1 += ((v0<<4) + KEY[2]) ^ (v0 + sum) ^ ((v0>>5) + KEY[3]);  
  }                                              /* end cycle */
  v[0]=v0; v[1]=v1;
}       

void decrypt (uint16_t* v) {
    uint16_t v0=v[0], v1=v[1], sum=0xC6EF, i;  /* set up */
    uint16_t delta=0x9e37;                     /* a key schedule constant */
    for (i=0; i<32; i++) {                     /* basic cycle start */
        v1 -= ((v0<<4) + KEY[2]) ^ (v0 + sum) ^ ((v0>>5) + KEY[3]);
        v0 -= ((v1<<4) + KEY[0]) ^ (v1 + sum) ^ ((v1>>5) + KEY[1]);
        sum -= delta;
    }                                              /* end cycle */
    v[0]=v0; v[1]=v1;
}

int main()
{
        // uint16_t is the same as an unsigned short
        // equal to 2 bytes or 16 bits
        // each hex is a nibble so 0xFFFF or 65535 is max val
        uint16_t v[] = {0xFFFF, 0xFFFF};

        encrypt(v);

        printf(" Encrypted: ");
        printf("[ %X %X ]", v[0], v[1]);

        decrypt(v);
        printf("\n Decrypted: ");
        printf("[ %X %X ]", v[0], v[1]);
        printf("\n");

        return 0;
}

1 个答案:

答案 0 :(得分:4)

您没有在解密中为sum设置正确的值。加密后sum的值为0xC6E0。在解密中设置该值而不是0xC6EF

sum=0xC6E0;