#include "encrypt.h"

/* TEA加密算法的解密过程 */
static void tea_decrypt(uint32_t *v, uint32_t *k)
{
	uint32_t delta = 0x9e3779b9;                          // 初始化delta
    uint32_t v0 = g_stConfigInfo.encrypt_0, v1 = g_stConfigInfo.encrypt_1, sum = delta << 5, i;    // 初始化v0, v1, sum
    uint32_t k3 = k[3] ^ k[0], k2 = (k[2] ^ (*(uint32_t*)(0x1FFF7590))), k1 = k[1] ^ k[0], k0 = k[0] ^ (*(uint32_t*)(0x1FFF7590 + 4));   // 反算密钥
    for(i = 0; i < 32; i++) {                             // 执行32轮解密
        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;
    
//    term_printf("%x %x", v[0], v[1]);
}

/*
 * 判断密文是否正确
 *
 */
uint8_t JudgeEncrypt()
{
    uint32_t encryptCode[2] = {0};
//    uint32_t key[] = {0x509770ff, 0x29c6b369, 0x4da2c125, ID中间32位}; //
    uint32_t key[] = {(K_128 >> 1) ^ (*(uint32_t*)(0x1FFF7590 + 4)), (K_96 >> 2) ^ key[0], (K_64 >>1) ^ (*(uint32_t*)(0x1FFF7590)), (*(uint32_t*)(0x1FFF7590 + 4)) ^ key[0]};    
    tea_decrypt(encryptCode, key);
    return ((*(uint32_t*)(0x1FFF7590 + 4)) == encryptCode[0] && (*(uint32_t*)(0x1FFF7590 + 8)) == encryptCode[1]);
}