blob: a82c9ccaa94fe4a7a6a36729378c7901de575efe [file] [log] [blame]
Adam Langley839b8812015-05-26 11:36:46 -07001/* 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
Adam Langley839b8812015-05-26 11:36:46 -070021#include "internal.h"
22
23
24static const struct argument kArguments[] = {
25 {
Adam Langley839b8812015-05-26 11:36:46 -070026 "-bits", kOptionalArgument,
27 "The number of bits in the modulus (default: 2048)",
28 },
29 {
30 "", kOptionalArgument, "",
31 },
32};
33
34bool GenerateRSAKey(const std::vector<std::string> &args) {
35 std::map<std::string, std::string> args_map;
36
37 if (!ParseKeyValueArguments(&args_map, args, kArguments)) {
38 PrintUsage(kArguments);
39 return false;
40 }
41
David Benjamin4a2cc282017-04-10 18:20:55 -040042 unsigned bits;
43 if (!GetUnsigned(&bits, "-bits", 2048, args_map)) {
Adam Langley839b8812015-05-26 11:36:46 -070044 PrintUsage(kArguments);
45 return false;
46 }
47
Matt Braithwaited17d74d2016-08-17 20:10:28 -070048 bssl::UniquePtr<RSA> rsa(RSA_new());
49 bssl::UniquePtr<BIGNUM> e(BN_new());
50 bssl::UniquePtr<BIO> bio(BIO_new_fp(stdout, BIO_NOCLOSE));
Adam Langley839b8812015-05-26 11:36:46 -070051
52 if (!BN_set_word(e.get(), RSA_F4) ||
David Benjamin4a2cc282017-04-10 18:20:55 -040053 !RSA_generate_key_ex(rsa.get(), bits, e.get(), NULL) ||
Adam Langley839b8812015-05-26 11:36:46 -070054 !PEM_write_bio_RSAPrivateKey(bio.get(), rsa.get(), NULL /* cipher */,
55 NULL /* key */, 0 /* key len */,
56 NULL /* password callback */,
57 NULL /* callback arg */)) {
58 ERR_print_errors_fp(stderr);
59 return false;
60 }
61
62 return true;
63}