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_RSA
18
19 #include "crypt_rsa.h"
20 #include "rsa_local.h"
21 #include "crypt_errno.h"
22 #include "crypt_utils.h"
23 #include "securec.h"
24 #include "bsl_sal.h"
25 #include "bsl_err_internal.h"
26
CRYPT_RSA_NewCtx(void)27 CRYPT_RSA_Ctx *CRYPT_RSA_NewCtx(void)
28 {
29 CRYPT_RSA_Ctx *keyCtx = NULL;
30 keyCtx = BSL_SAL_Malloc(sizeof(CRYPT_RSA_Ctx));
31 if (keyCtx == NULL) {
32 BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
33 return NULL;
34 }
35 (void)memset_s(keyCtx, sizeof(CRYPT_RSA_Ctx), 0, sizeof(CRYPT_RSA_Ctx));
36 BSL_SAL_ReferencesInit(&(keyCtx->references));
37 return keyCtx;
38 }
39
CRYPT_RSA_NewCtxEx(void * libCtx)40 CRYPT_RSA_Ctx *CRYPT_RSA_NewCtxEx(void *libCtx)
41 {
42 CRYPT_RSA_Ctx *keyCtx = CRYPT_RSA_NewCtx();
43 if (keyCtx == NULL) {
44 return NULL;
45 }
46 keyCtx->libCtx = libCtx;
47 return keyCtx;
48 }
49
RSAPubKeyDupCtx(CRYPT_RSA_PubKey * pubKey)50 static CRYPT_RSA_PubKey *RSAPubKeyDupCtx(CRYPT_RSA_PubKey *pubKey)
51 {
52 CRYPT_RSA_PubKey *newPubKey = BSL_SAL_Malloc(sizeof(CRYPT_RSA_PubKey));
53 if (newPubKey == NULL) {
54 BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
55 return NULL;
56 }
57
58 (void)memset_s(newPubKey, sizeof(CRYPT_RSA_PubKey), 0, sizeof(CRYPT_RSA_PubKey));
59
60 GOTO_ERR_IF_SRC_NOT_NULL(newPubKey->e, pubKey->e, BN_Dup(pubKey->e), CRYPT_MEM_ALLOC_FAIL);
61 GOTO_ERR_IF_SRC_NOT_NULL(newPubKey->n, pubKey->n, BN_Dup(pubKey->n), CRYPT_MEM_ALLOC_FAIL);
62
63 newPubKey->mont = BN_MontCreate(pubKey->n);
64 if (newPubKey->mont == NULL) {
65 BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
66 goto ERR;
67 }
68
69 return newPubKey;
70
71 ERR:
72 RSA_FREE_PUB_KEY(newPubKey);
73 return NULL;
74 }
75
RSAPriKeyDupCtx(CRYPT_RSA_PrvKey * prvKey)76 static CRYPT_RSA_PrvKey *RSAPriKeyDupCtx(CRYPT_RSA_PrvKey *prvKey)
77 {
78 CRYPT_RSA_PrvKey *newPriKey = BSL_SAL_Malloc(sizeof(CRYPT_RSA_PrvKey));
79 if (newPriKey == NULL) {
80 BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
81 return NULL;
82 }
83
84 (void)memset_s(newPriKey, sizeof(CRYPT_RSA_PrvKey), 0, sizeof(CRYPT_RSA_PrvKey));
85
86 GOTO_ERR_IF_SRC_NOT_NULL(newPriKey->n, prvKey->n, BN_Dup(prvKey->n), CRYPT_MEM_ALLOC_FAIL);
87 GOTO_ERR_IF_SRC_NOT_NULL(newPriKey->d, prvKey->d, BN_Dup(prvKey->d), CRYPT_MEM_ALLOC_FAIL);
88 GOTO_ERR_IF_SRC_NOT_NULL(newPriKey->p, prvKey->p, BN_Dup(prvKey->p), CRYPT_MEM_ALLOC_FAIL);
89 GOTO_ERR_IF_SRC_NOT_NULL(newPriKey->q, prvKey->q, BN_Dup(prvKey->q), CRYPT_MEM_ALLOC_FAIL);
90 GOTO_ERR_IF_SRC_NOT_NULL(newPriKey->dP, prvKey->dP, BN_Dup(prvKey->dP), CRYPT_MEM_ALLOC_FAIL);
91 GOTO_ERR_IF_SRC_NOT_NULL(newPriKey->dQ, prvKey->dQ, BN_Dup(prvKey->dQ), CRYPT_MEM_ALLOC_FAIL);
92 GOTO_ERR_IF_SRC_NOT_NULL(newPriKey->qInv, prvKey->qInv, BN_Dup(prvKey->qInv), CRYPT_MEM_ALLOC_FAIL);
93 GOTO_ERR_IF_SRC_NOT_NULL(newPriKey->e, prvKey->e, BN_Dup(prvKey->e), CRYPT_MEM_ALLOC_FAIL);
94
95 return newPriKey;
96 ERR:
97 RSA_FREE_PRV_KEY(newPriKey);
98 return NULL;
99 }
100
RSAParaDupCtx(CRYPT_RSA_Para * para)101 static CRYPT_RSA_Para *RSAParaDupCtx(CRYPT_RSA_Para *para)
102 {
103 CRYPT_RSA_Para *newPara = BSL_SAL_Malloc(sizeof(CRYPT_RSA_Para));
104 if (newPara == NULL) {
105 BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
106 return NULL;
107 }
108
109 (void)memset_s(newPara, sizeof(CRYPT_RSA_Para), 0, sizeof(CRYPT_RSA_Para));
110
111 newPara->bits = para->bits;
112 GOTO_ERR_IF_SRC_NOT_NULL(newPara->e, para->e, BN_Dup(para->e), CRYPT_MEM_ALLOC_FAIL);
113 GOTO_ERR_IF_SRC_NOT_NULL(newPara->p, para->p, BN_Dup(para->p), CRYPT_MEM_ALLOC_FAIL);
114 GOTO_ERR_IF_SRC_NOT_NULL(newPara->q, para->q, BN_Dup(para->q), CRYPT_MEM_ALLOC_FAIL);
115 return newPara;
116
117 ERR:
118 RSA_FREE_PARA(newPara);
119 return NULL;
120 }
121
122 #if defined(HITLS_CRYPTO_RSA_BLINDING) || defined(HITLS_CRYPTO_RSA_BSSA)
RSABlindDupCtx(RSA_Blind * blind)123 static RSA_Blind *RSABlindDupCtx(RSA_Blind *blind)
124 {
125 RSA_Blind *newBlind = BSL_SAL_Malloc(sizeof(RSA_Blind));
126 if (newBlind == NULL) {
127 BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
128 return NULL;
129 }
130
131 (void)memset_s(newBlind, sizeof(RSA_Blind), 0, sizeof(RSA_Blind));
132
133 GOTO_ERR_IF_SRC_NOT_NULL(newBlind->r, blind->r, BN_Dup(blind->r), CRYPT_MEM_ALLOC_FAIL);
134 GOTO_ERR_IF_SRC_NOT_NULL(newBlind->rInv, blind->rInv, BN_Dup(blind->rInv), CRYPT_MEM_ALLOC_FAIL);
135 return newBlind;
136
137 ERR:
138 RSA_BlindFreeCtx(newBlind);
139 return NULL;
140 }
141 #endif
142
143 #ifdef HITLS_CRYPTO_RSA_BSSA
RSABssADupCtx(RSA_BlindParam * blind)144 static RSA_BlindParam *RSABssADupCtx(RSA_BlindParam *blind)
145 {
146 RSA_BlindParam *newBlind = BSL_SAL_Calloc(1u, sizeof(RSA_BlindParam));
147 if (newBlind == NULL) {
148 BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
149 return NULL;
150 }
151 if (blind->type == RSABSSA) {
152 GOTO_ERR_IF_SRC_NOT_NULL(newBlind->para.bssa, blind->para.bssa,
153 RSABlindDupCtx(blind->para.bssa), CRYPT_MEM_ALLOC_FAIL);
154 newBlind->type = RSABSSA;
155 return newBlind;
156 }
157 ERR:
158 BSL_SAL_FREE(newBlind);
159 return NULL;
160 }
161 #endif
162
CRYPT_RSA_DupCtx(CRYPT_RSA_Ctx * keyCtx)163 CRYPT_RSA_Ctx *CRYPT_RSA_DupCtx(CRYPT_RSA_Ctx *keyCtx)
164 {
165 if (keyCtx == NULL) {
166 BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
167 return NULL;
168 }
169 CRYPT_RSA_Ctx *newKeyCtx = NULL;
170 newKeyCtx = BSL_SAL_Malloc(sizeof(CRYPT_RSA_Ctx));
171 if (newKeyCtx == NULL) {
172 BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
173 return NULL;
174 }
175
176 (void)memset_s(newKeyCtx, sizeof(CRYPT_RSA_Ctx), 0, sizeof(CRYPT_RSA_Ctx));
177
178 newKeyCtx->flags = keyCtx->flags;
179 (void)memcpy_s(&(newKeyCtx->pad), sizeof(RSAPad), &(keyCtx->pad), sizeof(RSAPad));
180
181 GOTO_ERR_IF_SRC_NOT_NULL(newKeyCtx->prvKey, keyCtx->prvKey, RSAPriKeyDupCtx(keyCtx->prvKey), CRYPT_MEM_ALLOC_FAIL);
182 GOTO_ERR_IF_SRC_NOT_NULL(newKeyCtx->pubKey, keyCtx->pubKey, RSAPubKeyDupCtx(keyCtx->pubKey), CRYPT_MEM_ALLOC_FAIL);
183 #ifdef HITLS_CRYPTO_RSA_BLINDING
184 GOTO_ERR_IF_SRC_NOT_NULL(newKeyCtx->scBlind, keyCtx->scBlind, RSABlindDupCtx(keyCtx->scBlind),
185 CRYPT_MEM_ALLOC_FAIL);
186 #endif
187 #ifdef HITLS_CRYPTO_RSA_BSSA
188 if (keyCtx->blindParam != NULL) {
189 GOTO_ERR_IF_SRC_NOT_NULL(newKeyCtx->blindParam, keyCtx->blindParam,
190 RSABssADupCtx(keyCtx->blindParam), CRYPT_MEM_ALLOC_FAIL);
191 }
192 #endif
193 GOTO_ERR_IF_SRC_NOT_NULL(newKeyCtx->para, keyCtx->para, RSAParaDupCtx(keyCtx->para), CRYPT_MEM_ALLOC_FAIL);
194 BSL_SAL_ReferencesInit(&(newKeyCtx->references));
195 return newKeyCtx;
196
197 ERR:
198 CRYPT_RSA_FreeCtx(newKeyCtx);
199 return NULL;
200 }
201
GetRsaParam(const BSL_Param * params,int32_t type,const uint8_t ** value,uint32_t * valueLen)202 static int32_t GetRsaParam(const BSL_Param *params, int32_t type, const uint8_t **value, uint32_t *valueLen)
203 {
204 const BSL_Param *temp = BSL_PARAM_FindConstParam(params, type);
205 if (temp == NULL || temp->valueLen == 0 || temp->value == NULL) {
206 BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
207 return CRYPT_INVALID_ARG;
208 }
209
210 *value = temp->value;
211 *valueLen = temp->valueLen;
212 return CRYPT_SUCCESS;
213 }
214
GetRsaBits(const BSL_Param * params,uint32_t * bits)215 static int32_t GetRsaBits(const BSL_Param *params, uint32_t *bits)
216 {
217 uint32_t bitsLen = sizeof(*bits);
218 const BSL_Param *temp = BSL_PARAM_FindConstParam(params, CRYPT_PARAM_RSA_BITS);
219 if (temp == NULL) {
220 BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
221 return CRYPT_INVALID_ARG;
222 }
223
224 int32_t ret = BSL_PARAM_GetValue(temp, CRYPT_PARAM_RSA_BITS, BSL_PARAM_TYPE_UINT32, bits, &bitsLen);
225 if (ret != BSL_SUCCESS || *bits < RSA_MIN_MODULUS_BITS || *bits > RSA_MAX_MODULUS_BITS) {
226 BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG);
227 return CRYPT_INVALID_ARG;
228 }
229
230 return CRYPT_SUCCESS;
231 }
232
ValidateRsaParams(uint32_t eLen,uint32_t bits)233 static int32_t ValidateRsaParams(uint32_t eLen, uint32_t bits)
234 {
235 /* the length of e cannot be greater than bits */
236 if (eLen > BN_BITS_TO_BYTES(bits)) {
237 BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_KEY_BITS);
238 return CRYPT_RSA_ERR_KEY_BITS;
239 }
240 return CRYPT_SUCCESS;
241 }
242
CRYPT_RSA_NewPara(const BSL_Param * para)243 CRYPT_RSA_Para *CRYPT_RSA_NewPara(const BSL_Param *para)
244 {
245 const uint8_t *e = NULL;
246 uint32_t eLen = 0;
247 int32_t ret = GetRsaParam(para, CRYPT_PARAM_RSA_E, &e, &eLen);
248 if (ret != CRYPT_SUCCESS) {
249 return NULL;
250 }
251 uint32_t bits = 0;
252 ret = GetRsaBits(para, &bits);
253 if (ret != CRYPT_SUCCESS) {
254 return NULL;
255 }
256 ret = ValidateRsaParams(eLen, bits);
257 if (ret != CRYPT_SUCCESS) {
258 return NULL;
259 }
260 CRYPT_RSA_Para *retPara = BSL_SAL_Malloc(sizeof(CRYPT_RSA_Para));
261 if (retPara == NULL) {
262 BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
263 return NULL;
264 }
265 retPara->bits = bits;
266 retPara->e = BN_Create(bits);
267 retPara->p = BN_Create(bits);
268 retPara->q = BN_Create(bits);
269 if (retPara->e == NULL || retPara->p == NULL || retPara->q == NULL) {
270 BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
271 goto ERR;
272 }
273 ret = BN_Bin2Bn(retPara->e, e, eLen);
274 if (ret != CRYPT_SUCCESS) {
275 BSL_ERR_PUSH_ERROR(ret);
276 goto ERR;
277 }
278 if (BN_BITS_TO_BYTES(bits) > RSA_SMALL_MODULUS_BYTES && BN_Bytes(retPara->e) > RSA_MAX_PUBEXP_BYTES) {
279 BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_KEY_BITS);
280 goto ERR;
281 }
282 return retPara;
283 ERR:
284 CRYPT_RSA_FreePara(retPara);
285 return NULL;
286 }
287
CRYPT_RSA_FreePara(CRYPT_RSA_Para * para)288 void CRYPT_RSA_FreePara(CRYPT_RSA_Para *para)
289 {
290 if (para == NULL) {
291 return;
292 }
293 BN_Destroy(para->e);
294 BN_Destroy(para->p);
295 BN_Destroy(para->q);
296 BSL_SAL_FREE(para);
297 }
298
RSA_FreePrvKey(CRYPT_RSA_PrvKey * prvKey)299 void RSA_FreePrvKey(CRYPT_RSA_PrvKey *prvKey)
300 {
301 if (prvKey == NULL) {
302 return;
303 }
304 BN_Destroy(prvKey->n);
305 BN_Destroy(prvKey->d);
306 BN_Destroy(prvKey->p);
307 BN_Destroy(prvKey->q);
308 BN_Destroy(prvKey->e);
309 BN_Destroy(prvKey->dP);
310 BN_Destroy(prvKey->dQ);
311 BN_Destroy(prvKey->qInv);
312 BSL_SAL_FREE(prvKey);
313 }
314
RSA_FreePubKey(CRYPT_RSA_PubKey * pubKey)315 void RSA_FreePubKey(CRYPT_RSA_PubKey *pubKey)
316 {
317 if (pubKey == NULL) {
318 return;
319 }
320 BN_Destroy(pubKey->n);
321 BN_Destroy(pubKey->e);
322 BN_MontDestroy(pubKey->mont);
323 BSL_SAL_FREE(pubKey);
324 }
325
CRYPT_RSA_FreeCtx(CRYPT_RSA_Ctx * ctx)326 void CRYPT_RSA_FreeCtx(CRYPT_RSA_Ctx *ctx)
327 {
328 if (ctx == NULL) {
329 return;
330 }
331 int i = 0;
332 BSL_SAL_AtomicDownReferences(&(ctx->references), &i);
333 if (i > 0) {
334 return;
335 }
336
337 BSL_SAL_ReferencesFree(&(ctx->references));
338 RSA_FREE_PARA(ctx->para);
339 RSA_FREE_PRV_KEY(ctx->prvKey);
340 RSA_FREE_PUB_KEY(ctx->pubKey);
341 #ifdef HITLS_CRYPTO_RSA_BLINDING
342 RSA_BlindFreeCtx(ctx->scBlind);
343 ctx->scBlind = NULL;
344 #endif
345 #ifdef HITLS_CRYPTO_RSA_BSSA
346 if (ctx->blindParam != NULL) {
347 if (ctx->blindParam->type == RSABSSA) {
348 RSA_BlindFreeCtx(ctx->blindParam->para.bssa);
349 }
350 BSL_SAL_FREE(ctx->blindParam);
351 }
352 #endif
353 BSL_SAL_CleanseData((void *)(&(ctx->pad)), sizeof(RSAPad));
354 BSL_SAL_FREE(ctx->label.data);
355 BSL_SAL_FREE(ctx);
356 }
357
IsRSASetParamValid(const CRYPT_RSA_Para * para)358 static int32_t IsRSASetParamValid(const CRYPT_RSA_Para *para)
359 {
360 if (para == NULL || para->e == NULL) {
361 BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
362 return CRYPT_NULL_INPUT;
363 }
364 if (para->bits > RSA_MAX_MODULUS_BITS || para->bits < RSA_MIN_MODULUS_BITS) {
365 BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_KEY_BITS);
366 return CRYPT_RSA_ERR_KEY_BITS;
367 }
368
369 if (BN_GetBit(para->e, 0) != true || BN_IsLimb(para->e, 1) == true) {
370 BSL_ERR_PUSH_ERROR(CRYPT_RSA_ERR_E_VALUE);
371 return CRYPT_RSA_ERR_E_VALUE;
372 }
373 return CRYPT_SUCCESS;
374 }
375
CRYPT_RSA_DupPara(const CRYPT_RSA_Para * para)376 CRYPT_RSA_Para *CRYPT_RSA_DupPara(const CRYPT_RSA_Para *para)
377 {
378 CRYPT_RSA_Para *paraCopy = BSL_SAL_Malloc(sizeof(CRYPT_RSA_Para));
379 if (paraCopy == NULL) {
380 BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
381 return NULL;
382 }
383 paraCopy->bits = para->bits;
384 paraCopy->e = BN_Dup(para->e);
385 paraCopy->p = BN_Dup(para->p);
386 paraCopy->q = BN_Dup(para->q);
387 if (paraCopy->e == NULL || paraCopy->p == NULL || paraCopy->q == NULL) {
388 BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
389 RSA_FREE_PARA(paraCopy);
390 return NULL;
391 }
392
393 return paraCopy;
394 }
395
CRYPT_RSA_SetPara(CRYPT_RSA_Ctx * ctx,const BSL_Param * para)396 int32_t CRYPT_RSA_SetPara(CRYPT_RSA_Ctx *ctx, const BSL_Param *para)
397 {
398 if (ctx == NULL) {
399 BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
400 return CRYPT_NULL_INPUT;
401 }
402 CRYPT_RSA_Para *rsaPara = CRYPT_RSA_NewPara(para);
403 if (rsaPara == NULL) {
404 BSL_ERR_PUSH_ERROR(CRYPT_EAL_ERR_NEW_PARA_FAIL);
405 return CRYPT_EAL_ERR_NEW_PARA_FAIL;
406 }
407 int32_t ret = IsRSASetParamValid(rsaPara);
408 if (ret != CRYPT_SUCCESS) {
409 RSA_FREE_PARA(rsaPara);
410 return ret;
411 }
412 (void)memset_s(&(ctx->pad), sizeof(RSAPad), 0, sizeof(RSAPad));
413 RSA_FREE_PARA(ctx->para);
414 RSA_FREE_PRV_KEY(ctx->prvKey);
415 RSA_FREE_PUB_KEY(ctx->pubKey);
416 ctx->para = rsaPara;
417 return CRYPT_SUCCESS;
418 }
419
RSA_NewPrvKey(uint32_t bits)420 CRYPT_RSA_PrvKey *RSA_NewPrvKey(uint32_t bits)
421 {
422 CRYPT_RSA_PrvKey *priKey = BSL_SAL_Malloc(sizeof(CRYPT_RSA_PrvKey));
423 if (priKey == NULL) {
424 BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
425 return NULL;
426 }
427 priKey->n = BN_Create(bits);
428 priKey->d = BN_Create(bits);
429 priKey->p = BN_Create(bits >> 1);
430 priKey->q = BN_Create(bits >> 1);
431 priKey->e = BN_Create(bits >> 1);
432 priKey->dP = BN_Create(bits >> 1);
433 priKey->dQ = BN_Create(bits >> 1);
434 priKey->qInv = BN_Create(bits >> 1);
435 bool creatFailed = (priKey->n == NULL || priKey->d == NULL || priKey->e == NULL || priKey->p == NULL ||
436 priKey->q == NULL || priKey->dP == NULL || priKey->dQ == NULL || priKey->qInv == NULL);
437 if (creatFailed) {
438 BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
439 RSA_FREE_PRV_KEY(priKey);
440 }
441 return priKey;
442 }
443
RSA_NewPubKey(uint32_t bits)444 CRYPT_RSA_PubKey *RSA_NewPubKey(uint32_t bits)
445 {
446 CRYPT_RSA_PubKey *pubKey = BSL_SAL_Malloc(sizeof(CRYPT_RSA_PubKey));
447 if (pubKey == NULL) {
448 BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
449 return NULL;
450 }
451 pubKey->n = BN_Create(bits);
452 pubKey->e = BN_Create(bits);
453 pubKey->mont = NULL;
454 if (pubKey->n == NULL || pubKey->e == NULL) {
455 BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
456 RSA_FREE_PUB_KEY(pubKey);
457 }
458 return pubKey;
459 }
460
CRYPT_RSA_GetBits(const CRYPT_RSA_Ctx * ctx)461 uint32_t CRYPT_RSA_GetBits(const CRYPT_RSA_Ctx *ctx)
462 {
463 if (ctx == NULL) {
464 return 0;
465 }
466 if (ctx->para != NULL) {
467 return ctx->para->bits;
468 }
469 if (ctx->prvKey != NULL) {
470 return BN_Bits(ctx->prvKey->n);
471 }
472 if (ctx->pubKey != NULL) {
473 return BN_Bits(ctx->pubKey->n);
474 }
475 return 0;
476 }
477
478 #if defined(HITLS_CRYPTO_RSA_SIGN) || defined(HITLS_CRYPTO_RSA_VERIFY)
CRYPT_RSA_GetSignLen(const CRYPT_RSA_Ctx * ctx)479 uint32_t CRYPT_RSA_GetSignLen(const CRYPT_RSA_Ctx *ctx)
480 {
481 return BN_BITS_TO_BYTES(CRYPT_RSA_GetBits(ctx));
482 }
483 #endif
484
485 #ifdef HITLS_CRYPTO_RSA_GEN
GetRandomX(void * libCtx,BN_BigNum * X,uint32_t nlen,bool isP)486 static int32_t GetRandomX(void *libCtx, BN_BigNum *X, uint32_t nlen, bool isP)
487 {
488 /*
489 * The FIPS 185-5 Appendix B.9 required √2(2 ^(nlen/2 - 1)) <= x <= ((2 ^(nlen/2) - 1))
490 * hence we can limit it as follows:
491 * √2 ~= 1.41421 < 1.5 -->
492 * √2(2 ^(nlen/2 - 1)) < 1.5 * (2 ^(nlen/2 - 1))
493 * next, we need to prove 1.5 * (2 ^(nlen/2 - 1)) <= ((2 ^(nlen/2) - 1))
494 * --> let x = 2 ^(nlen/2), 1.5 * (x/2) ≤ x - 1
495 * --> (3/4) x ≤ x - 1
496 * --> x >= 4, obviously correct.
497 * And, 1.5 * 2 ^(nlen/2 - 1) = 2 ^ (nlen/2 - 1) + 2 ^ (nlen/2 - 2);
498 * If we follow these steps to construct the bigNum:
499 * i. Randomly generate a random number, the most significant bit is (nlen / 2).
500 * ii. Set the (nlen/2 - 1) bits.
501 * We can obtain the x, satisfied [ 1.5 * 2 ^(nlen/2 - 1), ((2 ^(nlen/2) - 1) ].
502 */
503 if ((nlen % 2) == 0) {
504 return BN_RandEx(libCtx, X, nlen >> 1, BN_RAND_TOP_TWOBIT, BN_RAND_BOTTOM_NOBIT);
505 }
506 /*
507 * Meanwhile, if nlen is odd, We need to consider p, q separately.
508 */
509 if (isP) {
510 /*
511 * left : √2(2 ^(nlen/2 - 1)) < 2 ^ ⌊ (nlen / 2) ⌋
512 * right: if nlen is odd, 2 ^ (nlen/2) - 1 == 2 ^ ( ⌊ (nlen)/2 ⌋ + 1/2) - 1 == √2 * 2 ^ (⌊ (nlen)/2 ⌋) - 1
513 * if we want left <= right:
514 * 2 ^ ⌊ (nlen / 2) ⌋ < √2 * 2 ^ (⌊ (nlen)/2 ⌋) - 1
515 * --> 2 ^ ⌊ (nlen / 2) ⌋ < 1.4 * 2 ^ (⌊ (nlen)/2 ⌋) - 1
516 * --> 1 < 0.4 * 2 ^ (⌊ (nlen)/2 ⌋)
517 * --> nlen >= 3, obviously correct.
518 * hence, We can obtain the x, set the (nlen)/2 + 1 bits.
519 */
520 return BN_RandEx(libCtx, X, (nlen + 1) >> 1, BN_RAND_TOP_ONEBIT, BN_RAND_BOTTOM_NOBIT);
521 }
522 return BN_RandEx(libCtx, X, nlen >> 1, BN_RAND_TOP_TWOBIT, BN_RAND_BOTTOM_NOBIT);
523 }
524
525 /*
526 * Ref: FIPS 186-5: Table A.1
527 * Get the maximum lengths of p1, p2, q1, and q2.
528 */
GetAuxiliaryPrimeBitLen(uint32_t nlen)529 static uint32_t GetAuxiliaryPrimeBitLen(uint32_t nlen)
530 {
531 if (nlen <= 3071) {
532 return 141;
533 } else if (nlen <= 4095) {
534 return 171;
535 } else {
536 return 201;
537 }
538 }
539
540 /*
541 * Ref: FIPS 186-5: Table A.1
542 * Get the maximum lengths of p, q.
543 */
GetProbableNoLimitedBitLen(uint32_t nlen)544 static uint32_t GetProbableNoLimitedBitLen(uint32_t nlen)
545 {
546 if (nlen <= 3071) {
547 return 1007;
548 } else if (nlen <= 4095) {
549 return 1518;
550 } else {
551 return 2030;
552 }
553 }
554
555 /*
556 * Ref: FIPS 186-5: Table B.1
557 * Get minimum number of rounds of M-R testing when generating auxiliary primes.
558 */
GetAuxPrimeMillerCheckTimes(uint32_t auxBits)559 static uint32_t GetAuxPrimeMillerCheckTimes(uint32_t auxBits)
560 {
561 if (auxBits <= 170) {
562 return 38; // Error probability = 2 ^ (-112)
563 } else if (auxBits <= 200) {
564 return 41; // Error probability = 2 ^ (-128)
565 } else {
566 return 44; // Error probability = 2 ^ (-144)
567 }
568 }
569
570 /*
571 * Ref: FIPS 186-5: Table B.1
572 * Get minimum number of rounds of M-R testing when generating probable primes.
573 */
GetProbPrimeMillerCheckTimes(uint32_t proBits)574 static uint32_t GetProbPrimeMillerCheckTimes(uint32_t proBits)
575 {
576 if (proBits < 1536) {
577 return 5;
578 }
579 return 4;
580 }
581
GenAuxPrime(BN_BigNum * Xp,uint32_t auxBits,BN_Optimizer * opt)582 static int32_t GenAuxPrime(BN_BigNum *Xp, uint32_t auxBits, BN_Optimizer *opt)
583 {
584 int32_t ret = BN_RandEx(BN_OptimizerGetLibCtx(opt), Xp, auxBits, BN_RAND_TOP_ONEBIT, BN_RAND_BOTTOM_ONEBIT);
585 if (ret != CRYPT_SUCCESS) {
586 BSL_ERR_PUSH_ERROR(ret);
587 return ret;
588 }
589 uint32_t auxPrimeCheck = GetAuxPrimeMillerCheckTimes(auxBits);
590 do {
591 ret = BN_PrimeCheck(Xp, auxPrimeCheck, opt, NULL);
592 if (ret == CRYPT_SUCCESS) {
593 return ret;
594 }
595 if (ret != CRYPT_BN_NOR_CHECK_PRIME) {
596 BSL_ERR_PUSH_ERROR(ret);
597 return ret;
598 }
599 ret = BN_AddLimb(Xp, Xp, 2); // Try with odd numbers every time.
600 if (ret != CRYPT_SUCCESS) {
601 BSL_ERR_PUSH_ERROR(ret);
602 return ret;
603 }
604 } while (true);
605 }
606
607 /*
608 * Ref: FIPS 186-5 B.9 Compute a Probable Prime Factor Based on Auxiliary Primes.
609 * The standard specifies that the length of two small primes should meet
610 * len(r1) + len(r2) ≤ (nlen/2) – log2(nlen/2) – 7
611 * If nlen = 1024, r1, r2 is obtained by search from 141 bits data, the above inequality is still satisfied.
612 * Hence, it's a only performance consideration for us to use this standard for 1024-bit rsa key-Gen.
613 */
GenPrimeWithAuxiliaryPrime(uint32_t auxBits,uint32_t proBits,BN_BigNum * Xp,BN_BigNum * p,const CRYPT_RSA_Para * para,bool isP,BN_Optimizer * opt)614 static int32_t GenPrimeWithAuxiliaryPrime(uint32_t auxBits, uint32_t proBits, BN_BigNum *Xp, BN_BigNum *p,
615 const CRYPT_RSA_Para *para, bool isP, BN_Optimizer *opt)
616 {
617 uint32_t auxRoom = BITS_TO_BN_UNIT(auxBits);
618 int32_t ret = OptimizerStart(opt); // use the optimizer
619 if (ret != CRYPT_SUCCESS) {
620 BSL_ERR_PUSH_ERROR(ret);
621 return ret;
622 }
623 uint32_t probPrimeCheck = GetProbPrimeMillerCheckTimes(proBits);
624 BN_BigNum *r1 = OptimizerGetBn(opt, auxRoom);
625 BN_BigNum *r2 = OptimizerGetBn(opt, auxRoom);
626 BN_BigNum *r1Double = OptimizerGetBn(opt, auxRoom);
627 BN_BigNum *primeCheck = OptimizerGetBn(opt, auxRoom);
628 BN_BigNum *r2Inv = OptimizerGetBn(opt, auxRoom);
629 BN_BigNum *r1DoubleInv = OptimizerGetBn(opt, auxRoom);
630 BN_BigNum *R = OptimizerGetBn(opt, auxRoom);
631 BN_BigNum *pMinusOne = OptimizerGetBn(opt, BITS_TO_BN_UNIT(proBits));
632 uint32_t bits = isP ? (para->bits + 1) >> 1 : (para->bits >> 1); // Avoid the bit is odd.
633 uint32_t iterRound = 20 * bits; // Step 9 specifies that the iteration round is 20 * (nlen/2);
634 if (r1 == NULL || r2 == NULL || r1Double == NULL || primeCheck == NULL || r2Inv == NULL ||
635 r1DoubleInv == NULL || R == NULL || pMinusOne == NULL) {
636 ret = CRYPT_BN_OPTIMIZER_GET_FAIL;
637 OptimizerEnd(opt);
638 return ret;
639 }
640
641 ret = GenAuxPrime(r1, auxBits, opt);
642 if (ret != CRYPT_SUCCESS) {
643 BSL_ERR_PUSH_ERROR(ret);
644 OptimizerEnd(opt);
645 return ret;
646 }
647 GOTO_ERR_IF(GenAuxPrime(r2, auxBits, opt), ret);
648 GOTO_ERR_IF(BN_Lshift(r1Double, r1, 1), ret);
649 // Step 1: check 2r1, r2 are coprime.
650 GOTO_ERR_IF(BN_Gcd(primeCheck, r1Double, r2, opt), ret);
651 if (!BN_IsOne(primeCheck)) {
652 ret = CRYPT_RSA_NOR_KEYGEN_FAIL;
653 BSL_ERR_PUSH_ERROR(CRYPT_RSA_NOR_KEYGEN_FAIL);
654 goto ERR;
655 }
656 // Step 2: cal R = (r2^-1 mod 2r1) * r2 - ((2 * r1)^-1 mod r2) * (2 * r1)
657 GOTO_ERR_IF(BN_ModInv(r2Inv, r2, r1Double, opt), ret); // (r2^-1 mod 2r1) * r2
658 GOTO_ERR_IF(BN_Mul(r2Inv, r2, r2Inv, opt), ret);
659 // ((2 * r1)^-1 mod r2) * (2 * r1)
660 GOTO_ERR_IF(BN_ModInv(r1DoubleInv, r1Double, r2, opt), ret);
661 GOTO_ERR_IF(BN_Mul(r1DoubleInv, r1Double, r1DoubleInv, opt), ret);
662 // get R.
663 GOTO_ERR_IF(BN_Sub(R, r2Inv, r1DoubleInv), ret);
664 do {
665 // Step 3: get x, √2(2 ^(nlen/2 - 1)) <= x <= ((2 ^(nlen/2) - 1))
666 GOTO_ERR_IF(GetRandomX(BN_OptimizerGetLibCtx(opt), Xp, para->bits, isP), ret);
667 // Step 4: Y = X + ((R – X) mod 2r1r2
668 GOTO_ERR_IF(BN_Mul(r1, r1Double, r2, opt), ret); // 2r1r2
669 GOTO_ERR_IF(BN_ModSub(R, R, Xp, r1, opt), ret);
670 GOTO_ERR_IF(BN_Add(p, Xp, R), ret);
671 uint32_t i = 0;
672 for (; i < iterRound; i++) {
673 // Step 6: Check p ≥ 2 ^ (nlen/2)
674 if (BN_Bits(p) > bits) {
675 break;
676 }
677 // Step 7: Check the p - 1 and e are corprime.
678 GOTO_ERR_IF(BN_SubLimb(pMinusOne, p, 1), ret);
679 GOTO_ERR_IF(BN_Gcd(pMinusOne, pMinusOne, para->e, opt), ret);
680 if (BN_IsOne(pMinusOne)) {
681 // Step 7.1: Check the primality of p.
682 ret = BN_PrimeCheck(p, probPrimeCheck, opt, NULL);
683 if (ret == CRYPT_SUCCESS) { // We find a primes successfully.
684 goto ERR;
685 }
686 if (ret != CRYPT_BN_NOR_CHECK_PRIME) { // Another exception has occurred.
687 BSL_ERR_PUSH_ERROR(ret);
688 goto ERR;
689 }
690 }
691 // Step 10: Update p.
692 GOTO_ERR_IF(BN_Add(p, p, r1), ret);
693 }
694 // Step 9: check i ≥ 20 * (nlen/2).
695 if (i == iterRound) {
696 ret = CRYPT_RSA_NOR_KEYGEN_FAIL;
697 BSL_ERR_PUSH_ERROR(ret);
698 goto ERR;
699 }
700 } while (true);
701 ERR:
702 BN_Zeroize(r1);
703 BN_Zeroize(r2);
704 OptimizerEnd(opt);
705 return ret;
706 }
707
708 // ref: FIPS 186-5, A.1.6 & B.9
GenPQBasedOnProbPrimes(const CRYPT_RSA_Para * para,CRYPT_RSA_PrvKey * priKey,BN_Optimizer * opt)709 static int32_t GenPQBasedOnProbPrimes(const CRYPT_RSA_Para *para, CRYPT_RSA_PrvKey *priKey, BN_Optimizer *opt)
710 {
711 uint32_t proBits = GetProbableNoLimitedBitLen(para->bits);
712 uint32_t auxBits = GetAuxiliaryPrimeBitLen(para->bits);
713 // Used in check |Xp – Xq| ≤ 2^(nlen/2) – 100 or |p – q| ≤ 2^(nlen/2) – 100.
714 uint32_t secBits = ((para->bits + 1) >> 1) - 100;
715 uint32_t proRoom = BITS_TO_BN_UNIT(proBits);
716 int32_t ret = OptimizerStart(opt); // use the optimizer
717 if (ret != CRYPT_SUCCESS) {
718 BSL_ERR_PUSH_ERROR(ret);
719 return ret;
720 }
721 BN_BigNum *Xp = OptimizerGetBn(opt, proRoom);
722 BN_BigNum *Xq = OptimizerGetBn(opt, proRoom);
723 if (Xp == NULL || Xq == NULL) {
724 ret = CRYPT_BN_OPTIMIZER_GET_FAIL;
725 BSL_ERR_PUSH_ERROR(ret);
726 OptimizerEnd(opt);
727 return ret;
728 }
729 // Step 4: get p
730 ret = GenPrimeWithAuxiliaryPrime(auxBits, proBits, Xp, priKey->p, para, true, opt);
731 if (ret != CRYPT_SUCCESS) {
732 BN_Zeroize(Xp);
733 BSL_ERR_PUSH_ERROR(ret);
734 OptimizerEnd(opt);
735 return ret;
736 }
737 /*
738 * If |Xp – Xq| ≤ 2 ^ (2nlen/2 – 100) or |p – q| ≤ 2 ^ (2nlen/2 – 100), need to try again.
739 * We think there can ever be repeated many times here unless the 'random' is stuck.
740 * For example, nlen = 2048 and |Xp – Xq| ≤ 2 ^ (1024 – 100), it means that the most significant
741 * 99 bits of our Xq and Xp randomly generated are all identical. It's a low-probability event.
742 */
743 do {
744 // Step 5: get q
745 ret = GenPrimeWithAuxiliaryPrime(auxBits, proBits, Xq, priKey->q, para, false, opt);
746 if (ret != CRYPT_SUCCESS) {
747 BSL_ERR_PUSH_ERROR(ret);
748 goto ERR;
749 }
750 // Step 6: Check (|Xp – Xq| ≤ 2^(nlen/2) – 100) and (|p – q| ≤ 2^(nlen/2) – 100)
751 ret = BN_Sub(Xq, Xp, Xq); // Xq dont needs anymore, but Xp may be used.
752 if (ret != CRYPT_SUCCESS) {
753 BSL_ERR_PUSH_ERROR(ret);
754 goto ERR;
755 }
756 // |Xp – Xq| ≤ 2 ^ (2nlen/2 – 100) -> BN_Bits(Xp) <= secBits + 1 -> BN_Bits(Xp) < secBits
757 if (BN_Bits(Xq) < secBits) {
758 continue;
759 }
760 ret = BN_Sub(Xq, priKey->p, priKey->q);
761 if (ret != CRYPT_SUCCESS) {
762 BSL_ERR_PUSH_ERROR(ret);
763 goto ERR;
764 }
765 // |p – q| ≤ 2 ^ (2nlen/2 – 100)
766 if (BN_Bits(Xq) < secBits) {
767 continue;
768 }
769 break;
770 } while (true);
771 ERR:
772 BN_Zeroize(Xp);
773 BN_Zeroize(Xq);
774 OptimizerEnd(opt);
775 return ret;
776 }
777 #endif
778
RsaPrvKeyCalcND(const CRYPT_RSA_Para * para,CRYPT_RSA_Ctx * ctx,BN_BigNum * pMinusOne,BN_BigNum * qMinusOne,BN_Optimizer * optimizer)779 static int32_t RsaPrvKeyCalcND(
780 const CRYPT_RSA_Para *para, CRYPT_RSA_Ctx *ctx, BN_BigNum *pMinusOne, BN_BigNum *qMinusOne, BN_Optimizer *optimizer)
781 {
782 int32_t ret;
783 if (para == NULL) {
784 BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
785 return CRYPT_NULL_INPUT;
786 }
787 ret = OptimizerStart(optimizer);
788 if (ret != CRYPT_SUCCESS) {
789 BSL_ERR_PUSH_ERROR(ret);
790 return ret;
791 }
792 CRYPT_RSA_PrvKey *prvKey = ctx->prvKey;
793 BN_BigNum *l = OptimizerGetBn(optimizer, BITS_TO_BN_UNIT(para->bits));
794 BN_BigNum *u = OptimizerGetBn(optimizer, BITS_TO_BN_UNIT(para->bits));
795 if (l == NULL || u == NULL) {
796 BSL_ERR_PUSH_ERROR(CRYPT_BN_OPTIMIZER_GET_FAIL);
797 ret = CRYPT_BN_OPTIMIZER_GET_FAIL;
798 goto EXIT;
799 }
800 ret = BN_Mul(prvKey->n, prvKey->p, prvKey->q, optimizer);
801 if (ret != CRYPT_SUCCESS) {
802 BSL_ERR_PUSH_ERROR(ret);
803 goto EXIT;
804 }
805 ret = BN_Mul(l, pMinusOne, qMinusOne, optimizer);
806 if (ret != CRYPT_SUCCESS) {
807 BSL_ERR_PUSH_ERROR(ret);
808 goto EXIT;
809 }
810 ret = BN_Gcd(u, pMinusOne, qMinusOne, optimizer);
811 if (ret != CRYPT_SUCCESS) {
812 BSL_ERR_PUSH_ERROR(ret);
813 goto EXIT;
814 }
815 ret = BN_Div(l, NULL, l, u, optimizer);
816 if (ret != CRYPT_SUCCESS) {
817 BSL_ERR_PUSH_ERROR(ret);
818 goto EXIT;
819 }
820 ret = BN_ModInv(prvKey->d, para->e, l, optimizer);
821 if (ret != CRYPT_SUCCESS) {
822 BSL_ERR_PUSH_ERROR(ret);
823 }
824 EXIT:
825 OptimizerEnd(optimizer);
826 return ret;
827 }
828
829 // p, q [ => n, d] => dP dQ qInv
830 // ctx->para may be NULL when setting key
RSA_CalcPrvKey(const CRYPT_RSA_Para * para,CRYPT_RSA_Ctx * ctx,BN_Optimizer * optimizer)831 int32_t RSA_CalcPrvKey(const CRYPT_RSA_Para *para, CRYPT_RSA_Ctx *ctx, BN_Optimizer *optimizer)
832 {
833 int32_t ret;
834 CRYPT_RSA_PrvKey *prvKey = ctx->prvKey;
835 uint32_t needRoom = BITS_TO_BN_UNIT(BN_Bits(prvKey->p));
836 ret = OptimizerStart(optimizer);
837 if (ret != CRYPT_SUCCESS) {
838 BSL_ERR_PUSH_ERROR(ret);
839 return ret;
840 }
841 BN_BigNum *pMinusOne = OptimizerGetBn(optimizer, needRoom);
842 BN_BigNum *qMinusOne = OptimizerGetBn(optimizer, needRoom);
843 if (pMinusOne == NULL || qMinusOne == NULL) {
844 ret = CRYPT_BN_OPTIMIZER_GET_FAIL;
845 BSL_ERR_PUSH_ERROR(ret);
846 goto EXIT;
847 }
848 ret = BN_SubLimb(pMinusOne, prvKey->p, 1);
849 if (ret != CRYPT_SUCCESS) {
850 BSL_ERR_PUSH_ERROR(ret);
851 goto EXIT;
852 }
853 ret = BN_SubLimb(qMinusOne, prvKey->q, 1);
854 if (ret != CRYPT_SUCCESS) {
855 BSL_ERR_PUSH_ERROR(ret);
856 goto EXIT;
857 }
858 if (BN_IsZero(prvKey->n)) { // when generating key
859 ret = RsaPrvKeyCalcND(para, ctx, pMinusOne, qMinusOne, optimizer);
860 if (ret != CRYPT_SUCCESS) {
861 goto EXIT;
862 }
863 }
864 ret = BN_ModInv(prvKey->qInv, prvKey->q, prvKey->p, optimizer);
865 if (ret != CRYPT_SUCCESS) {
866 BSL_ERR_PUSH_ERROR(ret);
867 goto EXIT;
868 }
869 ret = BN_Div(NULL, prvKey->dP, prvKey->d, pMinusOne, optimizer);
870 if (ret != CRYPT_SUCCESS) {
871 BSL_ERR_PUSH_ERROR(ret);
872 goto EXIT;
873 }
874 ret = BN_Div(NULL, prvKey->dQ, prvKey->d, qMinusOne, optimizer);
875 if (ret != CRYPT_SUCCESS) {
876 BSL_ERR_PUSH_ERROR(ret);
877 }
878 EXIT:
879 OptimizerEnd(optimizer);
880 return ret;
881 }
882
883 #ifdef HITLS_CRYPTO_RSA_GEN
884 /*
885 * In NIST SP 800-56B, Section 6.4.1.1, requiring we should perform a successful key-pair validation
886 * while generating the key pair.
887 */
RSA_KeyValidationCheck(CRYPT_RSA_Ctx * ctx,uint32_t bits)888 static int32_t RSA_KeyValidationCheck(CRYPT_RSA_Ctx *ctx, uint32_t bits)
889 {
890 int32_t ret;
891 BN_BigNum *val = BN_Create(1);
892 BN_BigNum *expect = BN_Create(bits);
893 if (val == NULL || expect == NULL) {
894 ret = CRYPT_MEM_ALLOC_FAIL;
895 BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
896 goto ERR;
897 }
898 // for performance reasons, we choose test num = 2.
899 (void)BN_SetLimb(val, 2); // val is not null, and the val-memory must be sufficient.
900 GOTO_ERR_IF(BN_MontExp(expect, val, ctx->prvKey->e, ctx->pubKey->mont, NULL), ret);
901 GOTO_ERR_IF(BN_MontExpConsttime(expect, expect, ctx->prvKey->d, ctx->pubKey->mont, NULL), ret);
902 if (BN_Cmp(val, expect) != 0) {
903 ret = CRYPT_RSA_KEYPAIRWISE_CONSISTENCY_FAILURE;
904 BSL_ERR_PUSH_ERROR(CRYPT_RSA_KEYPAIRWISE_CONSISTENCY_FAILURE);
905 goto ERR;
906 }
907 ERR:
908 BN_Destroy(val);
909 BN_Destroy(expect);
910 return ret;
911 }
912
CRYPT_RSA_Gen(CRYPT_RSA_Ctx * ctx)913 int32_t CRYPT_RSA_Gen(CRYPT_RSA_Ctx *ctx)
914 {
915 if (ctx == NULL || ctx->para == NULL) {
916 BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
917 return CRYPT_NULL_INPUT;
918 }
919
920 int32_t ret = CRYPT_MEM_ALLOC_FAIL;
921 BN_Optimizer *optimizer = NULL;
922 CRYPT_RSA_Ctx *newCtx = CRYPT_RSA_NewCtx();
923 if (newCtx == NULL) {
924 BSL_ERR_PUSH_ERROR(ret);
925 return ret;
926 }
927
928 newCtx->prvKey = RSA_NewPrvKey(ctx->para->bits);
929 newCtx->pubKey = RSA_NewPubKey(ctx->para->bits);
930 optimizer = BN_OptimizerCreate();
931 if (optimizer == NULL || newCtx->prvKey == NULL || newCtx->pubKey == NULL) {
932 BSL_ERR_PUSH_ERROR(ret);
933 goto ERR;
934 }
935 /*
936 * Currently, although the FIPS 186-5 standard does not support key generation of 1024 bits
937 * due to its low security, our interface does not lift this restriction.
938 * Meanwhile, the check of e is not added to ensure compatibility.
939 */
940 BN_OptimizerSetLibCtx(ctx->libCtx, optimizer);
941 ret = GenPQBasedOnProbPrimes(ctx->para, newCtx->prvKey, optimizer);
942 if (ret != CRYPT_SUCCESS) {
943 BN_OptimizerDestroy(optimizer);
944 BSL_ERR_PUSH_ERROR(ret);
945 goto ERR;
946 }
947
948 ret = RSA_CalcPrvKey(ctx->para, newCtx, optimizer);
949 BN_OptimizerDestroy(optimizer);
950 if (ret != CRYPT_SUCCESS) {
951 BSL_ERR_PUSH_ERROR(ret);
952 goto ERR;
953 }
954 GOTO_ERR_IF(BN_Copy(newCtx->pubKey->n, newCtx->prvKey->n), ret);
955 GOTO_ERR_IF(BN_Copy(newCtx->pubKey->e, ctx->para->e), ret);
956
957 GOTO_ERR_IF(BN_Copy(newCtx->prvKey->e, ctx->para->e), ret);
958
959 if ((newCtx->pubKey->mont = BN_MontCreate(newCtx->pubKey->n)) == NULL) {
960 ret = CRYPT_MEM_ALLOC_FAIL;
961 BSL_ERR_PUSH_ERROR(ret);
962 goto ERR;
963 }
964 ret = RSA_KeyValidationCheck(newCtx, ctx->para->bits);
965 if (ret != CRYPT_SUCCESS) {
966 goto ERR; // dont't push the stack repeatedly.
967 }
968 ShallowCopyCtx(ctx, newCtx);
969 BSL_SAL_FREE(newCtx);
970 return ret;
971 ERR:
972 CRYPT_RSA_FreeCtx(newCtx);
973 return ret;
974 }
975
ShallowCopyCtx(CRYPT_RSA_Ctx * ctx,CRYPT_RSA_Ctx * newCtx)976 void ShallowCopyCtx(CRYPT_RSA_Ctx *ctx, CRYPT_RSA_Ctx *newCtx)
977 {
978 RSA_FREE_PRV_KEY(ctx->prvKey);
979 RSA_FREE_PUB_KEY(ctx->pubKey);
980 #ifdef HITLS_CRYPTO_RSA_BLINDING
981 RSA_BlindFreeCtx(ctx->scBlind);
982 #endif
983 BSL_SAL_ReferencesFree(&(newCtx->references));
984
985 ctx->prvKey = newCtx->prvKey;
986 ctx->pubKey = newCtx->pubKey;
987 #ifdef HITLS_CRYPTO_RSA_BLINDING
988 ctx->scBlind = newCtx->scBlind;
989 #endif
990 ctx->pad = newCtx->pad;
991 ctx->flags = newCtx->flags;
992 }
993
994 #endif // HITLS_CRYPTO_RSA_GEN
995
996 #ifdef HITLS_CRYPTO_PROVIDER
IsExistPrvKeyParams(const BSL_Param * params)997 static bool IsExistPrvKeyParams(const BSL_Param *params)
998 {
999 const BSL_Param *d = BSL_PARAM_FindConstParam(params, CRYPT_PARAM_RSA_D);
1000 const BSL_Param *n = BSL_PARAM_FindConstParam(params, CRYPT_PARAM_RSA_N);
1001 const BSL_Param *p = BSL_PARAM_FindConstParam(params, CRYPT_PARAM_RSA_P);
1002 const BSL_Param *q = BSL_PARAM_FindConstParam(params, CRYPT_PARAM_RSA_Q);
1003 const BSL_Param *dp = BSL_PARAM_FindConstParam(params, CRYPT_PARAM_RSA_DP);
1004 const BSL_Param *dq = BSL_PARAM_FindConstParam(params, CRYPT_PARAM_RSA_DQ);
1005 const BSL_Param *qInv = BSL_PARAM_FindConstParam(params, CRYPT_PARAM_RSA_QINV);
1006 return n != NULL && d != NULL && (PARAMISNULL(p) == PARAMISNULL(q)) &&
1007 (PARAMISNULL(dp) == PARAMISNULL(dq)) && PARAMISNULL(dq) == PARAMISNULL(qInv);
1008 }
1009
IsExistPubKeyParams(const BSL_Param * params)1010 static bool IsExistPubKeyParams(const BSL_Param *params)
1011 {
1012 const BSL_Param *e = BSL_PARAM_FindConstParam(params, CRYPT_PARAM_RSA_E);
1013 const BSL_Param *n = BSL_PARAM_FindConstParam(params, CRYPT_PARAM_RSA_N);
1014 return e != NULL && n != NULL;
1015 }
1016
IsExistRsaParam(const BSL_Param * params)1017 static bool IsExistRsaParam(const BSL_Param *params)
1018 {
1019 const BSL_Param *bits = BSL_PARAM_FindConstParam(params, CRYPT_PARAM_RSA_BITS);
1020 const BSL_Param *e = BSL_PARAM_FindConstParam(params, CRYPT_PARAM_RSA_E);
1021 return bits != NULL && e != NULL;
1022 }
1023
CRYPT_RSA_Import(CRYPT_RSA_Ctx * ctx,const BSL_Param * params)1024 int32_t CRYPT_RSA_Import(CRYPT_RSA_Ctx *ctx, const BSL_Param *params)
1025 {
1026 int32_t ret = CRYPT_SUCCESS;
1027 if (IsExistPrvKeyParams(params)) {
1028 ret = CRYPT_RSA_SetPrvKey(ctx, params);
1029 if (ret != CRYPT_SUCCESS) {
1030 BSL_ERR_PUSH_ERROR(ret);
1031 return ret;
1032 }
1033 }
1034 if (IsExistPubKeyParams(params)) {
1035 ret = CRYPT_RSA_SetPubKey(ctx, params);
1036 if (ret != CRYPT_SUCCESS) {
1037 BSL_ERR_PUSH_ERROR(ret);
1038 return ret;
1039 }
1040 }
1041 if (IsExistRsaParam(params)) {
1042 ret = CRYPT_RSA_SetPara(ctx, params);
1043 if (ret != CRYPT_SUCCESS) {
1044 BSL_ERR_PUSH_ERROR(ret);
1045 return ret;
1046 }
1047 }
1048 const BSL_Param *mdIdParam = BSL_PARAM_FindConstParam(params, CRYPT_PARAM_RSA_MD_ID);
1049 const BSL_Param *mgf1IdParam = BSL_PARAM_FindConstParam(params, CRYPT_PARAM_RSA_MGF1_ID);
1050 const BSL_Param *saltLenParam = BSL_PARAM_FindConstParam(params, CRYPT_PARAM_RSA_SALTLEN);
1051 if (mdIdParam != NULL && mgf1IdParam != NULL && saltLenParam != NULL) {
1052 ret = CRYPT_RSA_Ctrl(ctx, CRYPT_CTRL_SET_RSA_EMSA_PSS, (void *)(uintptr_t)params, 0);
1053 } else if (mdIdParam != NULL && mdIdParam->valueType == BSL_PARAM_TYPE_INT32 && mdIdParam->value != NULL) {
1054 int32_t mdId = *(int32_t *)mdIdParam->value;
1055 ret = CRYPT_RSA_Ctrl(ctx, CRYPT_CTRL_SET_RSA_EMSA_PKCSV15, &mdId, sizeof(mdId));
1056 }
1057 if (ret != CRYPT_SUCCESS) {
1058 BSL_ERR_PUSH_ERROR(ret);
1059 }
1060 return ret;
1061 }
1062
InitRsaPubKeyParams(BSL_Param * params,uint32_t * index,uint8_t * buffer,uint32_t len)1063 static void InitRsaPubKeyParams(BSL_Param *params, uint32_t *index, uint8_t *buffer, uint32_t len)
1064 {
1065 (void)BSL_PARAM_InitValue(¶ms[*index], CRYPT_PARAM_RSA_E,
1066 BSL_PARAM_TYPE_OCTETS, buffer + ((*index) * len), len);
1067 (*index)++;
1068 (void)BSL_PARAM_InitValue(¶ms[*index], CRYPT_PARAM_RSA_N,
1069 BSL_PARAM_TYPE_OCTETS, buffer + ((*index) * len), len);
1070 (*index)++;
1071 }
1072
InitRsaPrvKeyParams(BSL_Param * params,uint32_t * index,uint8_t * buffer,uint32_t len)1073 static void InitRsaPrvKeyParams(BSL_Param *params, uint32_t *index, uint8_t *buffer, uint32_t len)
1074 {
1075 (void)BSL_PARAM_InitValue(¶ms[*index], CRYPT_PARAM_RSA_D,
1076 BSL_PARAM_TYPE_OCTETS, buffer + ((*index) * len), len);
1077 (*index)++;
1078 (void)BSL_PARAM_InitValue(¶ms[*index], CRYPT_PARAM_RSA_P,
1079 BSL_PARAM_TYPE_OCTETS, buffer + ((*index) * len), len);
1080 (*index)++;
1081 (void)BSL_PARAM_InitValue(¶ms[*index], CRYPT_PARAM_RSA_Q,
1082 BSL_PARAM_TYPE_OCTETS, buffer + ((*index) * len), len);
1083 (*index)++;
1084 (void)BSL_PARAM_InitValue(¶ms[*index], CRYPT_PARAM_RSA_DP,
1085 BSL_PARAM_TYPE_OCTETS, buffer + ((*index) * len), len);
1086 (*index)++;
1087 (void)BSL_PARAM_InitValue(¶ms[*index], CRYPT_PARAM_RSA_DQ,
1088 BSL_PARAM_TYPE_OCTETS, buffer + ((*index) * len), len);
1089 (*index)++;
1090 (void)BSL_PARAM_InitValue(¶ms[*index], CRYPT_PARAM_RSA_QINV,
1091 BSL_PARAM_TYPE_OCTETS, buffer + ((*index) * len), len);
1092 (*index)++;
1093 }
1094
ExportRsaPssParams(const CRYPT_RSA_Ctx * ctx,BSL_Param * params,uint32_t * index)1095 static void ExportRsaPssParams(const CRYPT_RSA_Ctx *ctx, BSL_Param *params, uint32_t *index)
1096 {
1097 (void)BSL_PARAM_InitValue(¶ms[*index], CRYPT_PARAM_RSA_MD_ID,
1098 BSL_PARAM_TYPE_UINT32, (void *)(uintptr_t)&ctx->pad.para.pss.mdId, sizeof(uint32_t));
1099 params[(*index)++].useLen = sizeof(uint32_t);
1100 (void)BSL_PARAM_InitValue(¶ms[*index], CRYPT_PARAM_RSA_MGF1_ID,
1101 BSL_PARAM_TYPE_UINT32, (void *)(uintptr_t)&ctx->pad.para.pss.mgfId, sizeof(uint32_t));
1102 params[(*index)++].useLen = sizeof(uint32_t);
1103 (void)BSL_PARAM_InitValue(¶ms[*index], CRYPT_PARAM_RSA_SALTLEN,
1104 BSL_PARAM_TYPE_UINT32, (void *)(uintptr_t)&ctx->pad.para.pss.saltLen, sizeof(uint32_t));
1105 params[(*index)++].useLen = sizeof(uint32_t);
1106 }
1107
ExportRsaPkcsParams(const CRYPT_RSA_Ctx * ctx,BSL_Param * params,uint32_t * index)1108 static void ExportRsaPkcsParams(const CRYPT_RSA_Ctx *ctx, BSL_Param *params, uint32_t *index)
1109 {
1110 (void)BSL_PARAM_InitValue(¶ms[*index], CRYPT_PARAM_RSA_MD_ID,
1111 BSL_PARAM_TYPE_UINT32, (void *)(uintptr_t)&ctx->pad.para.pkcsv15.mdId, sizeof(uint32_t));
1112 params[(*index)++].useLen = sizeof(uint32_t);
1113 }
1114
CRYPT_RSA_Export(const CRYPT_RSA_Ctx * ctx,BSL_Param * params)1115 int32_t CRYPT_RSA_Export(const CRYPT_RSA_Ctx *ctx, BSL_Param *params)
1116 {
1117 if (ctx == NULL || params == NULL) {
1118 BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT);
1119 return CRYPT_NULL_INPUT;
1120 }
1121 uint32_t index = 1;
1122 void *args = NULL;
1123 CRYPT_EAL_ProcessFuncCb processCb = NULL;
1124 uint32_t keyBits = CRYPT_RSA_GetBits(ctx);
1125 if (keyBits == 0) {
1126 BSL_ERR_PUSH_ERROR(CRYPT_RSA_NO_KEY_INFO);
1127 return CRYPT_RSA_NO_KEY_INFO;
1128 }
1129 uint32_t bytes = BN_BITS_TO_BYTES(keyBits);
1130 BSL_Param rsaParams[13] = {
1131 {CRYPT_PARAM_RSA_BITS, BSL_PARAM_TYPE_UINT32, &keyBits, sizeof(uint32_t), sizeof(uint32_t)},
1132 {0}, {0}, {0}, {0}, {0}, {0}, {0}, {0}, {0}, {0}, {0}, BSL_PARAM_END};
1133 int32_t ret = CRYPT_GetPkeyProcessParams(params, &processCb, &args);
1134 if (ret != CRYPT_SUCCESS) {
1135 BSL_ERR_PUSH_ERROR(ret);
1136 return ret;
1137 }
1138 uint8_t *buffer = BSL_SAL_Calloc(1, keyBits * 8);
1139 if (buffer == NULL) {
1140 BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL);
1141 return CRYPT_MEM_ALLOC_FAIL;
1142 }
1143 if (ctx->pubKey != NULL) {
1144 InitRsaPubKeyParams(rsaParams, &index, buffer, bytes);
1145 ret = CRYPT_RSA_GetPubKey(ctx, rsaParams);
1146 if (ret != CRYPT_SUCCESS) {
1147 BSL_SAL_Free(buffer);
1148 BSL_ERR_PUSH_ERROR(ret);
1149 return ret;
1150 }
1151 }
1152 if (ctx->prvKey != NULL) {
1153 InitRsaPrvKeyParams(rsaParams, &index, buffer, bytes);
1154 ret = CRYPT_RSA_GetPrvKey(ctx, rsaParams);
1155 if (ret != CRYPT_SUCCESS) {
1156 BSL_SAL_Free(buffer);
1157 BSL_ERR_PUSH_ERROR(ret);
1158 return ret;
1159 }
1160 }
1161 if (ctx->pad.type == EMSA_PSS) {
1162 ExportRsaPssParams(ctx, rsaParams, &index);
1163 } else if (ctx->pad.type == EMSA_PKCSV15) {
1164 ExportRsaPkcsParams(ctx, rsaParams, &index);
1165 }
1166 for (uint32_t i = 0; i < index; i++) {
1167 rsaParams[i].valueLen = rsaParams[i].useLen;
1168 }
1169 ret = processCb(rsaParams, args);
1170 BSL_SAL_Free(buffer);
1171 if (ret != CRYPT_SUCCESS) {
1172 BSL_ERR_PUSH_ERROR(ret);
1173 }
1174 return ret;
1175 }
1176 #endif // HITLS_CRYPTO_PROVIDER
1177 #endif /* HITLS_CRYPTO_RSA */
1178
1179