// in 实际数据,inlen实际数据长度,key密钥(16字节长度),out处理结果,outlen处理结果长度值
void encrypt_msg(unsigned char *in, int inlen, unsigned long *key, unsigned char *out, unsigned long *outlen)
{
register int m, i, j, count, [color=Red]p = 1[/color];
unsigned char q[12], *q1, *q2, *inp;
unsigned char mkey[8];
m = (inlen+10)%8; // 为什么不用m = (inlen)%8; 来保证明文长度为 8 整数倍 ????
if (m) m = 8-m;
q[0] = (rand()&0xf8) | m; // 加密结果不唯一的原因采用了随机数
i = j = 1;
while(m>0) {
q[i++] = rand()&0xff;
m --;
}
count = *outlen = 0; // 传入的outlen值岂不没有用?????
q2 = q1 = out;
memset(mkey, 0, sizeof(mkey));
while( [color=Red]p <= 2[/color] ) { // 初值p = 1确定了,这个循环执行2次
if (i <8) {
q[i++] = rand()&0xff;
p ++;
}
if (i == 8) { // 此时m=7,
for (i = 0; i <8; i ++)
q[i] ^= mkey[i];
encrypt_qword((unsigned long *)q, key, (unsigned long *)out); // TEA 加密算法
for (i = 0; i <8; i ++)
q1[i] ^= mkey[i];
q2 = q1;
q1 += 8;
count += 8;
memcpy(mkey, q, 8);
j = i = 0;
}
}
inp = in;
while (inlen > 0) {
if (i <8) {
q[i] = inp[0];
inp ++;
i ++;
inlen --;
}
if (i == 8) {
for (i = 0; i <8; i ++) {
if (j) q[i] ^= mkey[i];
else q[i] ^= q2[i];
}
j = 0;
encrypt_qword((unsigned long *)q, key, (unsigned long *)q1);
for (i = 0; i <8; i ++)
q1[i] ^= mkey[i];
count += 8;
memcpy(mkey, q, 8);
q2 = q1;
q1 += 8;
i = 0;
}
}
p = 1;
while (p <8) {
if (i <8) {
memset(q+i, 0, 4);
p++;
i++;
}
if (i == 8) {
for (i = 0; i <8; i ++)
q[i] ^= q2[i];
encrypt_qword((unsigned long *)q, key, (unsigned long *)q1);
for (i = 0; i <8; i ++)
q1[i] ^= mkey[i];
memcpy(mkey, q, 8);
count += 8;
q2 = q1;
q1 += 8;
i = 0;
}
}
*outlen = count;
}