kehuadong

十万个为什么 [算法] [加密解密] xxtea加密解密

// 翻转双字
// ---------------------------------------------------------------------------
static inline uint32_t reverse_4bytes(uint32_t v)
{
    return (v>>24&0xFF) | (v>>8&0xFF00) | (v<<8&0xFF0000) | (v<<24&0xFF000000);
}

// xxtea加解密算法
// ---------------------------------------------------------------------------

// 算法验证数据(如果算法是正确的,那么使用该密钥可以把明文加密为密文或者把密文解密为明文)
// 密钥 969B344E1FB6F316332FB4A500BF4F4F
// 明文 02 00 01 00 01 55 AA CC
// 密文 D6 E3 F6 32 6A 9B 31 4C

#define DELTA 0x9e3779b9
#define MX ((((z >> 5) ^ (y << 2)) + ((y >> 3) ^ (z << 4))) ^ ((sum ^ y) + (key[(p & 3) ^ e] ^ z)))

static void xxtea_encrypt(bool encrypt, uint32_t *v, uint32_t size, const uint32_t *key)
{
	if (s_frame.m_use_xxtea_key == false)
	{
		return;
	}

	// LSB转MSB
	for (uint32_t i = 0; i < size; i++)
	{
		v[i] = reverse_4bytes(v[i]);
	}

	uint32_t y, z, sum;
    uint32_t p, rounds, e;

	rounds = 6 + 52/size;

	// 加密
	if (encrypt)
	{
		/* Coding Part */
		sum = 0;
		z = v[size - 1];
		do
		{
			sum += DELTA;
			e = (sum >> 2) & 3;
			for (p = 0; p < size - 1; p++)
			{
				y = v[p + 1];
				z = v[p] += MX;
			}
			y = v[0];
			z = v[size - 1] += MX;
		} while (--rounds);
	}
	// 解密
	else
	{
		sum = rounds * DELTA;
		y = v[0];
		do
		{
			e = (sum >> 2) & 3;
			for (p = size - 1; p > 0; p--)
			{
				z = v[p - 1];
				y = v[p] -= MX;
			}
			z = v[size - 1];
			y = v[0] -= MX;
		} while ((sum -= DELTA) != 0);
	}

	// MSB转LSB
	for (uint32_t i = 0; i < size; i++)
	{
		v[i] = reverse_4bytes(v[i]);
	}
}

 

posted on 2024-08-09 10:17  kehuadong  阅读(12)  评论(0编辑  收藏  举报

导航