genrsa.cc 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. #include <openssl/bio.h>
  15. #include <openssl/bn.h>
  16. #include <openssl/err.h>
  17. #include <openssl/pem.h>
  18. #include <openssl/rsa.h>
  19. #include "internal.h"
  20. static const struct argument kArguments[] = {
  21. {
  22. "-bits", kOptionalArgument,
  23. "The number of bits in the modulus (default: 2048)",
  24. },
  25. {
  26. "", kOptionalArgument, "",
  27. },
  28. };
  29. bool GenerateRSAKey(const std::vector<std::string> &args) {
  30. std::map<std::string, std::string> args_map;
  31. if (!ParseKeyValueArguments(&args_map, args, kArguments)) {
  32. PrintUsage(kArguments);
  33. return false;
  34. }
  35. unsigned bits;
  36. if (!GetUnsigned(&bits, "-bits", 2048, args_map)) {
  37. PrintUsage(kArguments);
  38. return false;
  39. }
  40. bssl::UniquePtr<RSA> rsa(RSA_new());
  41. bssl::UniquePtr<BIGNUM> e(BN_new());
  42. bssl::UniquePtr<BIO> bio(BIO_new_fp(stdout, BIO_NOCLOSE));
  43. if (!BN_set_word(e.get(), RSA_F4) ||
  44. !RSA_generate_key_ex(rsa.get(), bits, e.get(), NULL) ||
  45. !PEM_write_bio_RSAPrivateKey(bio.get(), rsa.get(), NULL /* cipher */,
  46. NULL /* key */, 0 /* key len */,
  47. NULL /* password callback */,
  48. NULL /* callback arg */)) {
  49. ERR_print_errors_fp(stderr);
  50. return false;
  51. }
  52. return true;
  53. }