XTEA encryption in PHP and decryption in C

2020-07-27 04:58发布

I'm trying to establish communication between a website and an Arduino. I need to authenticate all the messages from my website to the Arduino, so I have found that the less time expensive way is using XTEA cryptography.

My PHP code for the website is:

mcrypt_encrypt(MCRYPT_XTEA, 'qwertyuiasdfghjk', 'asdfasdf', MCRYPT_MODE_ECB);

where "qwertyuiasdfghjk" is a 128 bits key and "asdfasdf" is a 64 bits message.

On the Arduino side I'm using:

void _xtea_dec(void* dest, const void* v, const void* k)
{
    uint8_t i;
    uint32_t v0=((uint32_t*)v)[0], v1=((uint32_t*)v)[1];
    uint32_t sum=0xC6EF3720, delta=0x9E3779B9;
    for(i=0; i<32; i++)
    {
        v1 -= ((v0 << 4 ^ v0 >> 5) + v0) ^ (sum + ((uint32_t*)k)[sum>>11 & 3]);
        sum -= delta;
        v0 -= ((v1 << 4 ^ v1 >> 5) + v1) ^ (sum + ((uint32_t*)k)[sum & 3]);
    }
    ((uint32_t*)dest)[0]=v0; ((uint32_t*)dest)[1]=v1;
}

where the parameters are:

char dest[9]; //Destination
char v[9]; //Encrypted message
char k[17]; //Key

but my decrypted message is far away from the original message... It still having 64 bits, but it is totally different...

What should I do?

(This is the first time that I ask a question here, usually I all my questions are solved somewhere in Stack Overflow...)

2条回答
小情绪 Triste *
2楼-- · 2020-07-27 05:31

Most likely your cipher keys are different. Make sure they are the same in both ends.

C:

  // "annoying monkey"
  uint32_t key[4] = {0x6f6e6e61, 0x676e6979, 0x6e6f6d20, 0x0079656b };

PHP:

 mcrypt_encrypt(MCRYPT_XTEA, 'annoying monkey', 'data', MCRYPT_MODE_ECB);
查看更多
再贱就再见
3楼-- · 2020-07-27 05:35

As far as I remember, the XTEA specification did not provide test vectors and your code does not seem to care about endianness. Most probably it is a matter of key or data assumed/being in the wrong endian. Look at the implementation of mcrypt_encrypt function in the PHP source.

查看更多
登录 后发表回答