intel / ipp-crypto

Apache License 2.0
317 stars 84 forks source link

SM4 OFB cannot decrypt #34

Closed xiaonan-INTC closed 3 years ago

xiaonan-INTC commented 3 years ago

hi, guys,

When I use SM4 OFB to encrypt and decrypt, I met a error as below: (gdb) p plainText $1 = "\252\252\252\252\273\273\273\273\314\314\314\314\335\335\335", <incomplete sequence \335> (gdb) p pEncrypt $2 = "\254\062\066ˆ\035\323\026\346A;N<u$\267" (gdb) p pDecrypt $3 = "_\335t\207\061\236\211k\207\036\327\332\341V̗"

The data is using example/sms4: sgxIpp8u plainText[SRC_LEN] = { 0xAA,0xAA,0xAA,0xAA,0xBB,0xBB,0xBB,0xBB, 0xCC,0xCC,0xCC,0xCC,0xDD,0xDD,0xDD,0xDD };

sgxIpp8u key[SGX_SM4_CFB_KEY_SIZE] = { 0x01,0x23,0x45,0x67,0x89,0xAB,0xCD,0xEF, 0xFE,0xDC,0xBA,0x98,0x76,0x54,0x32,0x10 };

sgxIpp8u iv[SGX_SM4_CFB_IV_SIZE] = { 0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07, 0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0E,0x0F };

And the test program is also using example/sms4, which replace ippsSMS4EncryptCBC/DecryptCBC(plainText, pOut, sizeof(plainText), pSMS4, iv) to ippsSMS4EncryptOFB/DecryptOFB(plainText, pOut, sizeof(plainText), 16, pSMS4, iv);

Could anyone help check if OFB works well or provide a successful example? Thanks a lot!

ElenaTyuleneva commented 3 years ago

Hello! Could you please provide the full source code you are running?

Possible problem may be in the following: SM4 Encryption and Decryption in OFB mode update the initialization vector and store it in iv. As a result, the decryption operation is called with an updated iv. To solve this you should make a copy of iv, for example:

...
Ipp8u iv_copy[SMS4_BLOCK_SIZE] = {};
memcpy(iv_copy, iv, sizeof(iv));
status = ippsSMS4EncryptOFB(plainText, cipherText, sizeof(plainText),16, pSMS4, iv_copy);
memcpy(iv_copy, iv, sizeof(iv));
status = ippsSMS4DecryptOFB(cipherText, pOut, sizeof(cipherText), 16, pSMS4, iv_copy);
...

Regards, Elena

xiaonan-INTC commented 3 years ago

Hello! Could you please provide the full source code you are running?

Possible problem may be in the following: SM4 Encryption and Decryption in OFB mode update the initialization vector and store it in iv. As a result, the decryption operation is called with an updated iv. To solve this you should make a copy of iv, for example:

...
Ipp8u iv_copy[SMS4_BLOCK_SIZE] = {};
memcpy(iv_copy, iv, sizeof(iv));
status = ippsSMS4EncryptOFB(plainText, cipherText, sizeof(plainText),16, pSMS4, iv_copy);
memcpy(iv_copy, iv, sizeof(iv));
status = ippsSMS4DecryptOFB(cipherText, pOut, sizeof(cipherText), 16, pSMS4, iv_copy);
...

Regards, Elena

Thanks a lot, Elena! Your solution works well for me! :)