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