Search code examples
javabouncycastleencryption

My XTEA implementation for BC doesn't work, why?


Bouncy castle already provide XTEA encryption using class XTEAEngine. The class attributes look like this:

private static final int rounds     = 32,
                         block_size = 8,
                         key_size   = 16,
                         delta      = 0x9E3779B9,
                         d_sum      = 0xC6EF3720; // sum on decrypt

But closed source C++ application uses following settings (with 32 rounds):

uint32 delta = 0x61C88647; uint32 sum = 0xC6EF3720;

So to change it, I've copied whole code of BC XTEAEngine class, named it XTEAEngine2 at changed delta. But now encryption does not work as expected:

arr given    : [11, 0, 10, 8, 0, 72, 105, 32, 116, 104, 101, 114, 101, 0, 0, 0] 
arr encrypted: [-128, -26, -32, 17, 7, 98, 80, -112, 26, -83, -11, 47, -124, -50, -80, 59] 
arr decrypted: [-106, 62, 110, -40, -56, -58, 18, -101, -38, -73, -83, 95, 18, -99, -84, -37]

Before my change everything was fine:

arr given    : [11, 0, 10, 8, 0, 72, 105, 32, 116, 104, 101, 114, 101, 0, 0, 0]
arr encrypted: [89, -95, -88, 120, -117, 39, 57, -126, 23, -74, 35, 105, -23, -7, -109, -27]
arr decrypted: [11, 0, 10, 8, 0, 72, 105, 32, 116, 104, 101, 114, 101, 0, 0, 0]

And I'm using BouncyCastle XTEA like this:

BlockCipher engine = new XTEAEngine[2]();
BufferedBlockCipher cipher = new BufferedBlockCipher(engine);
KeyParameter kp = new KeyParameter(keyArr);
 private byte[] callCipher( byte[] data )
    throws CryptoException {
        int    size =
                cipher.getOutputSize( data.length );
        byte[] result = new byte[ size ];
        int    olen = cipher.processBytes( data, 0,
                data.length, result, 0 );
        olen += cipher.doFinal( result, olen );

        if( olen < size ){
            byte[] tmp = new byte[ olen ];
            System.arraycopy(
                    result, 0, tmp, 0, olen );
            result = tmp;
        }

        return result;
    }


public synchronized byte[] encrypt( byte[] data )
    throws CryptoException {
        if( data == null || data.length == 0 ){
            return new byte[0];
        }

        cipher.init( true, kp );
        return callCipher( data );
    }

    public synchronized byte[] decrypt( byte[] data )
    throws CryptoException {
        if( data == null || data.length == 0 ){
            return new byte[0];
        }

        cipher.init( false, kp );
        return callCipher( data );
    }

Is anyone able to point my mistake? Because I believe that I made one somewhere. I even implemented XTEA completely on my own using algorithm specification from Wikipedia but same thing happened.


Solution

  • 0x9E3779B9 is the two's complement negative of 0x61C88647; this suggests to me that there's an addition vs a subtraction swapped somewhere.