1 /*
2 * This file is part of the openHiTLS project.
3 *
4 * openHiTLS is licensed under the Mulan PSL v2.
5 * You can use this software according to the terms and conditions of the Mulan PSL v2.
6 * You may obtain a copy of Mulan PSL v2 at:
7 *
8 * http://license.coscl.org.cn/MulanPSL2
9 *
10 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
11 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
12 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
13 * See the Mulan PSL v2 for more details.
14 */
15
16 #include "hitls_build.h"
17 #ifdef HITLS_CRYPTO_ELGAMAL
18
19 #include <stdbool.h>
20 #include "securec.h"
21 #include "bsl_sal.h"
22 #include "bsl_err_internal.h"
23 #include "crypt_errno.h"
24 #include "crypt_elgamal.h"
25 #include "elgamal_local.h"
26 #include "crypt_utils.h"
27 #include "crypt_params_key.h"
28
OriginalRoot(void * libCtx,BN_BigNum * g,const BN_BigNum * p,const BN_BigNum * q,uint32_t bits)29 int32_t OriginalRoot(void *libCtx, BN_BigNum *g, const BN_BigNum *p, const BN_BigNum *q, uint32_t bits)
30 {
31 if (g == NULL || p == NULL || q == NULL ) {
32 BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
33 return CRYPT_NULL_INPUT;
34 }
35
36 BN_Optimizer *optimizer = BN_OptimizerCreate();
37 if (optimizer == NULL) {
38 BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
39 return CRYPT_MEM_ALLOC_FAIL;
40 }
41
42 int32_t ret = CRYPT_MEM_ALLOC_FAIL;
43 BN_BigNum *x1 = BN_Create(bits);
44 BN_BigNum *x2 = BN_Create(bits);
45 BN_BigNum *xTop = BN_Create(bits);
46 if (x1 == NULL || x2 == NULL || xTop == NULL) {
47 BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
48 goto EXIT;
49 }
50
51 ret = BN_SubLimb(xTop, p, 1);
52 if (ret != CRYPT_SUCCESS) {
53 BSL_ERR_PUSH_ERROR(ret);
54 goto EXIT;
55 }
56
57 while (true) {
58 ret = BN_RandRangeEx(libCtx, g, xTop);
59 if (ret != CRYPT_SUCCESS) {
60 BSL_ERR_PUSH_ERROR(ret);
61 goto EXIT;
62 }
63
64 ret = BN_ModSqr(x1, g, p, optimizer);
65 if (ret != CRYPT_SUCCESS) {
66 BSL_ERR_PUSH_ERROR(ret);
67 goto EXIT;
68 }
69 if (BN_IsOne(x1)) {
70 continue;
71 }
72
73 ret = BN_ModExp(x2, g, q, p, optimizer);
74 if (ret != CRYPT_SUCCESS) {
75 BSL_ERR_PUSH_ERROR(ret);
76 goto EXIT;
77 }
78
79 if (!BN_IsOne(x2)) {
80 break;
81 }
82 }
83 EXIT:
84 BN_Destroy(xTop);
85 BN_Destroy(x2);
86 BN_Destroy(x1);
87 BN_OptimizerDestroy(optimizer);
88 return ret;
89 }
90
91 #endif /* HITLS_CRYPTO_ELGAMAL */