PHP中的XTEA加密和C中的解密

时间:2020-12-24 18:31:02

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.

我正在尝试在网站和Arduino之间建立通信。我需要验证从我的网站到Arduino的所有消息,所以我发现使用XTEA加密技术的时间更少。

My PHP code for the website is:

我的网站PHP代码是:

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

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

其中“qwertyuiasdfghjk”是128位密钥,“asdfasdf”是64位消息。

On the Arduino side I'm using:

在Arduino方面,我正在使用:

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...

但我的解密消息远离原始消息......它仍然有64位,但它完全不同......

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...)

(这是我第一次在这里提出一个问题,通常我的所有问题都在Stack Overflow中解决了......)

2 个解决方案

#1


2  

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

#2


2  

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.

据我所知,XTEA规范没有提供测试向量,你的代码似乎并不关心字节序。最有可能的是关键或数据假设/存在错误的结尾。查看PHP源代码中mcrypt_encrypt函数的实现。

#1


2  

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

#2


2  

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.

据我所知,XTEA规范没有提供测试向量,你的代码似乎并不关心字节序。最有可能的是关键或数据假设/存在错误的结尾。查看PHP源代码中mcrypt_encrypt函数的实现。