1 // Copyright 2019 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 5 #ifndef UTIL_CRYPTO_RSA_PRIVATE_KEY_H_ 6 #define UTIL_CRYPTO_RSA_PRIVATE_KEY_H_ 7 8 #include <openssl/base.h> 9 #include <openssl/evp.h> 10 #include <stddef.h> 11 #include <stdint.h> 12 13 #include <memory> 14 #include <vector> 15 16 #include "platform/base/error.h" 17 #include "platform/base/macros.h" 18 19 namespace openscreen { 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 class RSAPrivateKey { 24 public: 25 RSAPrivateKey(RSAPrivateKey&& other) noexcept = default; 26 RSAPrivateKey& operator=(RSAPrivateKey&& other) = default; 27 ~RSAPrivateKey(); 28 29 // Create a new random instance. Can return nullptr if initialization fails. 30 static ErrorOr<RSAPrivateKey> Create(uint16_t num_bits); 31 32 // Create a new instance by importing an existing private key. The format is 33 // an ASN.1-encoded PrivateKeyInfo block from PKCS #8. 34 static ErrorOr<RSAPrivateKey> CreateFromPrivateKeyInfo( 35 const std::vector<uint8_t>& input); 36 37 // Create a new instance from an existing EVP_PKEY, taking a 38 // reference to it. |key| must be an RSA key. 39 static ErrorOr<RSAPrivateKey> CreateFromKey(EVP_PKEY* key); 40 41 // Creates a copy of the object. 42 ErrorOr<RSAPrivateKey> Copy() const; 43 key()44 EVP_PKEY* key() { return key_.get(); } key()45 const EVP_PKEY* key() const { return key_.get(); } 46 47 // Exports the private key to a PKCS #8 PrivateKeyInfo block. 48 ErrorOr<std::vector<uint8_t>> ExportPrivateKey() const; 49 50 // Exports the public key to an X509 SubjectPublicKeyInfo block. 51 ErrorOr<std::vector<uint8_t>> ExportPublicKey() const; 52 53 private: 54 // Constructor is private. Use one of the Create*() methods above instead. 55 RSAPrivateKey(); 56 57 bssl::UniquePtr<EVP_PKEY> key_; 58 59 OSP_DISALLOW_COPY_AND_ASSIGN(RSAPrivateKey); 60 }; 61 62 } // namespace openscreen 63 64 #endif // UTIL_CRYPTO_RSA_PRIVATE_KEY_H_ 65