Closed truc0 closed 1 year ago
Link to PR #312
This issue may be related to the padding process in encryption. Here are some of my thoughts, feel free to point out my faults.
The problem maybe related to wrong padding strategy in encryption process.
The RFC5652 (aka PKCS#7) indicates that padding should always apply to the plaintext before encryption. Current implementation of SM4_CBC
encryption disables padding when len(plaintext) % 16 == 0
(see ehsm/core/Enclave/openssl_operation.cpp#L293).
Disabling padding mode when len(plaintext) % 16
results in ambiguity of the decrypted data (before removing padding) if the plaintext before encryption is as following:
00 01 02 03 04 05 06 07
08 09 0a 0b 04 04 04 04
The last 4 bytes is exact the same as the padding of the following plaintext:
00 01 02 03 04 05 06 07
08 09 0a 0b
To solve this problem, PKCS#7 enables padding even if len(plaintext) % k == 0
(k = 16
in this case). The plaintext with padding for the first example above should be:
00 01 02 03 04 05 06 07
08 09 0a 0b 04 04 04 04
10 10 10 10 10 10 10 10
10 10 10 10 10 10 10 10
The modification makes the decryption process clearer and guarantees the data is consistence after encryption and decryption.
Always enable padding mode in encryption should solve this issue.
Description
Padding of data is also returned as part of data in SM4_CBC decryption, which causes the inconsistence between plaintext and result of decryption.
Reproduction
The following script is a minimal reproduction. Save it to
bug.py
in theehsm/test
folder and run.The result should be:
Note
Note that the padding only occurs when
len(text) % 8 != 0
.