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