1e1051a39Sopenharmony_ci/*
2e1051a39Sopenharmony_ci * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
3e1051a39Sopenharmony_ci *
4e1051a39Sopenharmony_ci * Licensed under the Apache License 2.0 (the "License").  You may not use
5e1051a39Sopenharmony_ci * this file except in compliance with the License.  You can obtain a copy
6e1051a39Sopenharmony_ci * in the file LICENSE in the source distribution or at
7e1051a39Sopenharmony_ci * https://www.openssl.org/source/license.html
8e1051a39Sopenharmony_ci */
9e1051a39Sopenharmony_ci
10e1051a39Sopenharmony_ci#include "internal/deprecated.h" /* to be able to use EC_KEY and EC_GROUP */
11e1051a39Sopenharmony_ci
12e1051a39Sopenharmony_ci#include <openssl/err.h>
13e1051a39Sopenharmony_ci#include "crypto/sm2err.h"
14e1051a39Sopenharmony_ci#include "crypto/sm2.h"
15e1051a39Sopenharmony_ci#include <openssl/ec.h> /* EC_KEY and EC_GROUP functions */
16e1051a39Sopenharmony_ci
17e1051a39Sopenharmony_ci/*
18e1051a39Sopenharmony_ci * SM2 key generation is implemented within ec_generate_key() in
19e1051a39Sopenharmony_ci * crypto/ec/ec_key.c
20e1051a39Sopenharmony_ci */
21e1051a39Sopenharmony_ci
22e1051a39Sopenharmony_ciint ossl_sm2_key_private_check(const EC_KEY *eckey)
23e1051a39Sopenharmony_ci{
24e1051a39Sopenharmony_ci    int ret = 0;
25e1051a39Sopenharmony_ci    BIGNUM *max = NULL;
26e1051a39Sopenharmony_ci    const EC_GROUP *group = NULL;
27e1051a39Sopenharmony_ci    const BIGNUM *priv_key = NULL, *order = NULL;
28e1051a39Sopenharmony_ci
29e1051a39Sopenharmony_ci    if (eckey == NULL
30e1051a39Sopenharmony_ci            || (group = EC_KEY_get0_group(eckey)) == NULL
31e1051a39Sopenharmony_ci            || (priv_key = EC_KEY_get0_private_key(eckey)) == NULL
32e1051a39Sopenharmony_ci            || (order = EC_GROUP_get0_order(group)) == NULL ) {
33e1051a39Sopenharmony_ci        ERR_raise(ERR_LIB_SM2, ERR_R_PASSED_NULL_PARAMETER);
34e1051a39Sopenharmony_ci        return 0;
35e1051a39Sopenharmony_ci    }
36e1051a39Sopenharmony_ci
37e1051a39Sopenharmony_ci    /* range of SM2 private key is [1, n-1) */
38e1051a39Sopenharmony_ci    max = BN_dup(order);
39e1051a39Sopenharmony_ci    if (max == NULL || !BN_sub_word(max, 1))
40e1051a39Sopenharmony_ci        goto end;
41e1051a39Sopenharmony_ci    if (BN_cmp(priv_key, BN_value_one()) < 0
42e1051a39Sopenharmony_ci        || BN_cmp(priv_key, max) >= 0) {
43e1051a39Sopenharmony_ci        ERR_raise(ERR_LIB_SM2, SM2_R_INVALID_PRIVATE_KEY);
44e1051a39Sopenharmony_ci        goto end;
45e1051a39Sopenharmony_ci    }
46e1051a39Sopenharmony_ci    ret = 1;
47e1051a39Sopenharmony_ci
48e1051a39Sopenharmony_ci end:
49e1051a39Sopenharmony_ci    BN_free(max);
50e1051a39Sopenharmony_ci    return ret;
51e1051a39Sopenharmony_ci}
52