1 /* 2 * Copyright 2017-2024 The OpenSSL Project Authors. All Rights Reserved. 3 * Copyright 2017 BaishanCloud. All rights reserved. 4 * 5 * Licensed under the Apache License 2.0 (the "License"). You may not use 6 * this file except in compliance with the License. You can obtain a copy 7 * in the file LICENSE in the source distribution or at 8 * https://www.openssl.org/source/license.html 9 */ 10 11 #include <openssl/bn.h> 12 #include <openssl/err.h> 13 #include "rsa_local.h" 14 ossl_rsa_multip_info_free_ex(RSA_PRIME_INFO * pinfo)15void ossl_rsa_multip_info_free_ex(RSA_PRIME_INFO *pinfo) 16 { 17 /* free pp and pinfo only */ 18 BN_clear_free(pinfo->pp); 19 OPENSSL_free(pinfo); 20 } 21 ossl_rsa_multip_info_free(RSA_PRIME_INFO * pinfo)22void ossl_rsa_multip_info_free(RSA_PRIME_INFO *pinfo) 23 { 24 /* free an RSA_PRIME_INFO structure */ 25 BN_clear_free(pinfo->r); 26 BN_clear_free(pinfo->d); 27 BN_clear_free(pinfo->t); 28 ossl_rsa_multip_info_free_ex(pinfo); 29 } 30 ossl_rsa_multip_info_new(void)31RSA_PRIME_INFO *ossl_rsa_multip_info_new(void) 32 { 33 RSA_PRIME_INFO *pinfo; 34 35 /* create an RSA_PRIME_INFO structure */ 36 if ((pinfo = OPENSSL_zalloc(sizeof(RSA_PRIME_INFO))) == NULL) 37 return NULL; 38 if ((pinfo->r = BN_secure_new()) == NULL) 39 goto err; 40 if ((pinfo->d = BN_secure_new()) == NULL) 41 goto err; 42 if ((pinfo->t = BN_secure_new()) == NULL) 43 goto err; 44 if ((pinfo->pp = BN_secure_new()) == NULL) 45 goto err; 46 47 return pinfo; 48 49 err: 50 BN_free(pinfo->r); 51 BN_free(pinfo->d); 52 BN_free(pinfo->t); 53 BN_free(pinfo->pp); 54 OPENSSL_free(pinfo); 55 return NULL; 56 } 57 58 /* Refill products of primes */ ossl_rsa_multip_calc_product(RSA * rsa)59int ossl_rsa_multip_calc_product(RSA *rsa) 60 { 61 RSA_PRIME_INFO *pinfo; 62 BIGNUM *p1 = NULL, *p2 = NULL; 63 BN_CTX *ctx = NULL; 64 int i, rv = 0, ex_primes; 65 66 if ((ex_primes = sk_RSA_PRIME_INFO_num(rsa->prime_infos)) <= 0) { 67 /* invalid */ 68 goto err; 69 } 70 71 if ((ctx = BN_CTX_new()) == NULL) 72 goto err; 73 74 /* calculate pinfo->pp = p * q for first 'extra' prime */ 75 p1 = rsa->p; 76 p2 = rsa->q; 77 78 for (i = 0; i < ex_primes; i++) { 79 pinfo = sk_RSA_PRIME_INFO_value(rsa->prime_infos, i); 80 if (pinfo->pp == NULL) { 81 pinfo->pp = BN_secure_new(); 82 if (pinfo->pp == NULL) 83 goto err; 84 } 85 if (!BN_mul(pinfo->pp, p1, p2, ctx)) 86 goto err; 87 /* save previous one */ 88 p1 = pinfo->pp; 89 p2 = pinfo->r; 90 } 91 92 rv = 1; 93 err: 94 BN_CTX_free(ctx); 95 return rv; 96 } 97 ossl_rsa_multip_cap(int bits)98int ossl_rsa_multip_cap(int bits) 99 { 100 int cap = RSA_MAX_PRIME_NUM; 101 102 if (bits < 1024) 103 cap = 2; 104 else if (bits < 4096) 105 cap = 3; 106 else if (bits < 8192) 107 cap = 4; 108 109 if (cap > RSA_MAX_PRIME_NUM) 110 cap = RSA_MAX_PRIME_NUM; 111 112 return cap; 113 } 114