| 39 | using std::vector; |
| 40 | |
| 41 | Try<EVP_PKEY*> generate_private_rsa_key(int bits, unsigned long _exponent) |
| 42 | { |
| 43 | // Allocate the in-memory structure for the private key. |
| 44 | EVP_PKEY* private_key = EVP_PKEY_new(); |
| 45 | if (private_key == nullptr) { |
| 46 | return Error("Failed to allocate key: EVP_PKEY_new"); |
| 47 | } |
| 48 | |
| 49 | // Allocate space for the exponent. |
| 50 | BIGNUM* exponent = BN_new(); |
| 51 | if (exponent == nullptr) { |
| 52 | EVP_PKEY_free(private_key); |
| 53 | return Error("Failed to allocate exponent: BN_new"); |
| 54 | } |
| 55 | |
| 56 | // Assign the exponent. |
| 57 | if (BN_set_word(exponent, _exponent) != 1) { |
| 58 | BN_free(exponent); |
| 59 | EVP_PKEY_free(private_key); |
| 60 | return Error("Failed to set exponent: BN_set_word"); |
| 61 | } |
| 62 | |
| 63 | // Allocate the in-memory structure for the key pair. |
| 64 | RSA* rsa = RSA_new(); |
| 65 | if (rsa == nullptr) { |
| 66 | BN_free(exponent); |
| 67 | EVP_PKEY_free(private_key); |
| 68 | return Error("Failed to allocate RSA: RSA_new"); |
| 69 | } |
| 70 | |
| 71 | // Generate the RSA key pair. |
| 72 | if (RSA_generate_key_ex(rsa, bits, exponent, nullptr) != 1) { |
| 73 | RSA_free(rsa); |
| 74 | BN_free(exponent); |
| 75 | EVP_PKEY_free(private_key); |
| 76 | return Error(ERR_error_string(ERR_get_error(), nullptr)); |
| 77 | } |
| 78 | |
| 79 | // We no longer need the exponent, so let's free it. |
| 80 | BN_free(exponent); |
| 81 | |
| 82 | // Associate the RSA key with the private key. If this association |
| 83 | // is successful, then the RSA key will be freed when the private |
| 84 | // key is freed. |
| 85 | if (EVP_PKEY_assign_RSA(private_key, rsa) != 1) { |
| 86 | RSA_free(rsa); |
| 87 | EVP_PKEY_free(private_key); |
| 88 | return Error("Failed to assign RSA key: EVP_PKEY_assign_RSA"); |
| 89 | } |
| 90 | |
| 91 | return private_key; |
| 92 | } |
| 93 | |
| 94 | |
| 95 | Try<X509*> generate_x509( |
no outgoing calls