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. 4 5 #ifndef CRYPTO_RSA_PRIVATE_KEY_H_ 6 #define CRYPTO_RSA_PRIVATE_KEY_H_ 7 8 #include <stddef.h> 9 #include <stdint.h> 10 11 #include <memory> 12 #include <vector> 13 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" 18 19 namespace crypto { 20 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 { 25 public: 26 RSAPrivateKey(const RSAPrivateKey&) = delete; 27 RSAPrivateKey& operator=(const RSAPrivateKey&) = delete; 28 29 ~RSAPrivateKey(); 30 31 // Create a new random instance. Can return NULL if initialization fails. 32 static std::unique_ptr<RSAPrivateKey> Create(uint16_t num_bits); 33 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); 39 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 42 // failure. 43 static std::unique_ptr<RSAPrivateKey> CreateFromKey(EVP_PKEY* key); 44 key()45 EVP_PKEY* key() const { return key_.get(); } 46 47 // Creates a copy of the object. 48 std::unique_ptr<RSAPrivateKey> Copy() const; 49 50 // Exports the private key to a PKCS #8 PrivateKeyInfo block. 51 bool ExportPrivateKey(std::vector<uint8_t>* output) const; 52 53 // Exports the public key to an X509 SubjectPublicKeyInfo block. 54 bool ExportPublicKey(std::vector<uint8_t>* output) const; 55 56 private: 57 // Constructor is private. Use one of the Create*() methods above instead. 58 RSAPrivateKey(); 59 60 bssl::UniquePtr<EVP_PKEY> key_; 61 }; 62 63 } // namespace crypto 64 65 #endif // CRYPTO_RSA_PRIVATE_KEY_H_ 66