diff options
author | Liu-Ermeng <liuermeng2@huawei.com> | 2024-01-07 20:01:29 -0800 |
---|---|---|
committer | Tomas Mraz <tomas@openssl.org> | 2024-05-15 11:17:14 +0200 |
commit | 170620675dfd74f34bdcf8aba71dffeb07f3d533 (patch) | |
tree | 1b5b02052fb896b07c93ee5c53ab90a3882b5a21 /crypto/sm2 | |
parent | f6e469808501f52c7e8f8679d6c3290cf1c258b3 (diff) |
fix sm2 encryption implementation bug.
According to the "GB/T 32918.4-2016"
section 6.1 encryption, step A5:
If result of the "KDF" is all zeros, we should go back to
the begin(step A1).
section 7.1 decryption, step B4:
If result of the "KDF" is all zeros, we should raise error and exit.
Signed-off-by: Liu-Ermeng <liuermeng2@huawei.com>
Reviewed-by: Neil Horman <nhorman@openssl.org>
Reviewed-by: Tomas Mraz <tomas@openssl.org>
(Merged from https://github.com/openssl/openssl/pull/23210)
Diffstat (limited to 'crypto/sm2')
-rw-r--r-- | crypto/sm2/sm2_crypt.c | 31 |
1 files changed, 27 insertions, 4 deletions
diff --git a/crypto/sm2/sm2_crypt.c b/crypto/sm2/sm2_crypt.c index affa920fff..b7303af522 100644 --- a/crypto/sm2/sm2_crypt.c +++ b/crypto/sm2/sm2_crypt.c @@ -54,6 +54,18 @@ static size_t ec_field_size(const EC_GROUP *group) return BN_num_bytes(p); } +static int is_all_zeros(const unsigned char *msg, size_t msglen) +{ + unsigned char re = 0; + size_t i; + + for (i = 0; i < msglen; i++) { + re |= msg[i]; + } + + return re == 0 ? 1 : 0; +} + int ossl_sm2_plaintext_size(const unsigned char *ct, size_t ct_size, size_t *pt_size) { @@ -168,6 +180,11 @@ int ossl_sm2_encrypt(const EC_KEY *key, memset(ciphertext_buf, 0, *ciphertext_len); + msg_mask = OPENSSL_zalloc(msg_len); + if (msg_mask == NULL) + goto done; + +again: if (!BN_priv_rand_range_ex(k, order, 0, ctx)) { ERR_raise(ERR_LIB_SM2, ERR_R_INTERNAL_ERROR); goto done; @@ -187,10 +204,6 @@ int ossl_sm2_encrypt(const EC_KEY *key, goto done; } - msg_mask = OPENSSL_zalloc(msg_len); - if (msg_mask == NULL) - goto done; - /* X9.63 with no salt happens to match the KDF used in SM2 */ if (!ossl_ecdh_kdf_X9_63(msg_mask, msg_len, x2y2, 2 * field_size, NULL, 0, digest, libctx, propq)) { @@ -198,6 +211,11 @@ int ossl_sm2_encrypt(const EC_KEY *key, goto done; } + if (is_all_zeros(msg_mask, msg_len)) { + memset(x2y2, 0, 2 * field_size); + goto again; + } + for (i = 0; i != msg_len; ++i) msg_mask[i] ^= msg[i]; @@ -349,6 +367,11 @@ int ossl_sm2_decrypt(const EC_KEY *key, goto done; } + if (is_all_zeros(msg_mask, msg_len)) { + ERR_raise(ERR_LIB_SM2, SM2_R_INVALID_ENCODING); + goto done; + } + for (i = 0; i != msg_len; ++i) ptext_buf[i] = C2[i] ^ msg_mask[i]; |