| 6 | // |
| 7 | // https://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 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 "internal.h" |
| 22 |
| 23 |
| 24 | static const struct argument kArguments[] = { |
| 25 | { |
| 26 | "-bits", kOptionalArgument, |
| 27 | "The number of bits in the modulus (default: 2048)", |
| 28 | }, |
| 29 | { |
| 30 | "", kOptionalArgument, "", |
| 31 | }, |
| 32 | }; |
| 33 |
| 34 | bool 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 |
| 42 | unsigned bits; |
| 43 | if (!GetUnsigned(&bits, "-bits", 2048, args_map)) { |
| 44 | PrintUsage(kArguments); |
| 45 | return false; |
| 46 | } |
| 47 |
| 48 | bssl::UniquePtr<RSA> rsa(RSA_new()); |
| 49 | bssl::UniquePtr<BIGNUM> e(BN_new()); |
| 50 | bssl::UniquePtr<BIO> bio(BIO_new_fp(stdout, BIO_NOCLOSE)); |
| 51 |
| 52 | if (!BN_set_word(e.get(), RSA_F4) || |
| 53 | !RSA_generate_key_ex(rsa.get(), bits, e.get(), NULL) || |
| 54 | !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 | } |
| 64 |