TEA Java implementation

0

I am implementing a simple TEA algorithm with example data so I know that my output text (0x53452e77 903386e3) is wrong and should be 0x7556391b 2315d9f8. Any tips?

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));        
    }

}
java
encryption
asked on Stack Overflow Feb 10, 2019 by GeoffM • edited Feb 10, 2019 by MichaƂ Ziober

1 Answer

0

The change is to add & 0xfffffff0 and & 0x7ffffff to the for-loop when calculating L and R. These are known as bitmasks - masking an integer with 0x7ffffff ensures that a 32-bit quantity can't be signed (the most significant bit is 0), whilst masking with 0xfffffff0 ensures that the low four bits are zero.

Other minor change compared to what OP has done was use >> instead of >>>, but that has no impact on the result.

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));
    }
answered on Stack Overflow Feb 10, 2019 by vs97 • edited Feb 10, 2019 by vs97

User contributions licensed under CC BY-SA 3.0