我正在用示例数据实现简单的TEA算法,因此我知道我的输出文本(0x53452e77 903386e3)错误,应为0x7556391b 2315d9f8。有小费吗?
public class Driver {
public static void main(String[] args) {
int L = 0x12345678;
int R = 0x9abcdef;
int delta = 0x9e3779b9;
int sum = 0x0;
int[] key = {0xa56babcd,0xf000ffff,0xffffffff,0xabcdef01};
//Encrypt
for(int i = 0; i < 32; i++)
{
sum += delta;
L += ((R << 4) + key[0]) ^ (R + sum) ^ ((R >>> 5) + key[1]);
R += ((L << 4) + key[2]) ^ (L + sum) ^ ((L >>> 5) + key[3]);
}
System.out.println(String.format("0x%x", L) + " " + String.format("%x", R));
}
}
答案 0 :(得分:0)
更改是在计算L和R时将& 0xfffffff0
和& 0x7ffffff
添加到for循环中。这些称为位掩码-用0x7ffffff
掩码整数可确保32-不能对位数进行签名(最高有效位为0),而使用0xfffffff0
进行屏蔽可确保低四位为零。
与OP相比,其他较小的更改是使用>>
而不是>>>
,但这对结果没有影响。
public static void main(String[] args)
{
int L = 0x12345678;
int R = 0x9abcdef;
int delta = 0x9e3779b9;
int sum = 0x0;
int[] key = {0xa56babcd,0xf000ffff,0xffffffff,0xabcdef01};
//Encrypt
for(int i = 0; i < 32; i++)
{
sum += delta;
L += (R << 4 & 0xfffffff0) + key[0] ^ R + sum ^ (R >> 5 & 0x7ffffff) + key[1];
R += (L << 4 & 0xfffffff0) + key[2] ^ L + sum ^ (L >> 5 & 0x7ffffff) + key[3];
}
System.out.println(String.format("0x%x", L) + " " + String.format("%x", R));
}