| 1 |
/* Copyright (c) 2015, Google Inc. |
| 2 |
* |
| 3 |
* Permission to use, copy, modify, and/or distribute this software for any |
| 4 |
* purpose with or without fee is hereby granted, provided that the above |
| 5 |
* copyright notice and this permission notice appear in all copies. |
| 6 |
* |
| 7 |
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES |
| 8 |
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF |
| 9 |
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY |
| 10 |
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES |
| 11 |
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION |
| 12 |
* OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN |
| 13 |
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ |
| 14 |
|
| 15 |
#include <openssl/bio.h> |
| 16 |
#include <openssl/bn.h> |
| 17 |
#include <openssl/err.h> |
| 18 |
#include <openssl/pem.h> |
| 19 |
#include <openssl/rsa.h> |
| 20 |
|
| 21 |
#include "../crypto/test/scoped_types.h" |
| 22 |
#include "internal.h" |
| 23 |
|
| 24 |
|
| 25 |
static const struct argument kArguments[] = { |
| 26 |
{ |
| 27 |
"-nprimes", kOptionalArgument, |
| 28 |
"The number of primes to generate (default: 2)", |
| 29 |
}, |
| 30 |
{ |
| 31 |
"-bits", kOptionalArgument, |
| 32 |
"The number of bits in the modulus (default: 2048)", |
| 33 |
}, |
| 34 |
{ |
| 35 |
"", kOptionalArgument, "", |
| 36 |
}, |
| 37 |
}; |
| 38 |
|
| 39 |
bool GenerateRSAKey(const std::vector<std::string> &args) { |
| 40 |
std::map<std::string, std::string> args_map; |
| 41 |
|
| 42 |
if (!ParseKeyValueArguments(&args_map, args, kArguments)) { |
| 43 |
PrintUsage(kArguments); |
| 44 |
return false; |
| 45 |
} |
| 46 |
|
| 47 |
unsigned bits, nprimes = 0; |
| 48 |
if (!GetUnsigned(&bits, "-bits", 2048, args_map) || |
| 49 |
!GetUnsigned(&nprimes, "-nprimes", 2, args_map)) { |
| 50 |
PrintUsage(kArguments); |
| 51 |
return false; |
| 52 |
} |
| 53 |
|
| 54 |
ScopedRSA rsa(RSA_new()); |
| 55 |
ScopedBIGNUM e(BN_new()); |
| 56 |
ScopedBIO bio(BIO_new_fp(stdout, BIO_NOCLOSE)); |
| 57 |
|
| 58 |
if (!BN_set_word(e.get(), RSA_F4) || |
| 59 |
!RSA_generate_multi_prime_key(rsa.get(), bits, nprimes, e.get(), NULL) || |
| 60 |
!PEM_write_bio_RSAPrivateKey(bio.get(), rsa.get(), NULL /* cipher */, |
| 61 |
NULL /* key */, 0 /* key len */, |
| 62 |
NULL /* password callback */, |
| 63 |
NULL /* callback arg */)) { |
| 64 |
ERR_print_errors_fp(stderr); |
| 65 |
return false; |
| 66 |
} |
| 67 |
|
| 68 |
return true; |
| 69 |
} |