rsa_private_key.h 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // Copyright (c) 2012 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #ifndef CRYPTO_RSA_PRIVATE_KEY_H_
  5. #define CRYPTO_RSA_PRIVATE_KEY_H_
  6. #include <stddef.h>
  7. #include <stdint.h>
  8. #include <memory>
  9. #include <vector>
  10. #include "base/containers/span.h"
  11. #include "build/build_config.h"
  12. #include "crypto/crypto_export.h"
  13. #include "third_party/boringssl/src/include/openssl/base.h"
  14. namespace crypto {
  15. // Encapsulates an RSA private key. Can be used to generate new keys, export
  16. // keys to other formats, or to extract a public key.
  17. // TODO(hclam): This class should be ref-counted so it can be reused easily.
  18. class CRYPTO_EXPORT RSAPrivateKey {
  19. public:
  20. RSAPrivateKey(const RSAPrivateKey&) = delete;
  21. RSAPrivateKey& operator=(const RSAPrivateKey&) = delete;
  22. ~RSAPrivateKey();
  23. // Create a new random instance. Can return NULL if initialization fails.
  24. static std::unique_ptr<RSAPrivateKey> Create(uint16_t num_bits);
  25. // Create a new instance by importing an existing private key. The format is
  26. // an ASN.1-encoded PrivateKeyInfo block from PKCS #8. This can return NULL if
  27. // initialization fails.
  28. static std::unique_ptr<RSAPrivateKey> CreateFromPrivateKeyInfo(
  29. base::span<const uint8_t> input);
  30. // Create a new instance from an existing EVP_PKEY, taking a
  31. // reference to it. |key| must be an RSA key. Returns NULL on
  32. // failure.
  33. static std::unique_ptr<RSAPrivateKey> CreateFromKey(EVP_PKEY* key);
  34. EVP_PKEY* key() const { return key_.get(); }
  35. // Creates a copy of the object.
  36. std::unique_ptr<RSAPrivateKey> Copy() const;
  37. // Exports the private key to a PKCS #8 PrivateKeyInfo block.
  38. bool ExportPrivateKey(std::vector<uint8_t>* output) const;
  39. // Exports the public key to an X509 SubjectPublicKeyInfo block.
  40. bool ExportPublicKey(std::vector<uint8_t>* output) const;
  41. private:
  42. // Constructor is private. Use one of the Create*() methods above instead.
  43. RSAPrivateKey();
  44. bssl::UniquePtr<EVP_PKEY> key_;
  45. };
  46. } // namespace crypto
  47. #endif // CRYPTO_RSA_PRIVATE_KEY_H_