Meng-Huan Yu | 4cbaddc | 2019-05-08 18:31:53 +0800 | [diff] [blame] | 1 | // Copyright 2019 The Chromium OS 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 LIBHWSEC_CRYPTO_UTILITY_H_ |
| 6 | #define LIBHWSEC_CRYPTO_UTILITY_H_ |
| 7 | |
| 8 | #include <cstdint> |
| 9 | #include <string> |
| 10 | #include <vector> |
| 11 | |
| 12 | #include <base/optional.h> |
Wei-Cheng Xiao | 174e16f | 2020-02-20 16:12:55 +0800 | [diff] [blame] | 13 | #include <brillo/secure_blob.h> |
Meng-Huan Yu | 4cbaddc | 2019-05-08 18:31:53 +0800 | [diff] [blame] | 14 | #include <crypto/scoped_openssl_types.h> |
Wei-Cheng Xiao | 174e16f | 2020-02-20 16:12:55 +0800 | [diff] [blame] | 15 | #include <openssl/bn.h> |
Meng-Huan Yu | 4cbaddc | 2019-05-08 18:31:53 +0800 | [diff] [blame] | 16 | |
| 17 | #include "libhwsec/hwsec_export.h" |
| 18 | |
| 19 | namespace hwsec { |
| 20 | |
Wei-Cheng Xiao | 174e16f | 2020-02-20 16:12:55 +0800 | [diff] [blame] | 21 | // RAII version of OpenSSL BN_CTX, with auto-initialization on instantiation and |
| 22 | // auto-cleanup on leaving scope. |
| 23 | class HWSEC_EXPORT ScopedBN_CTX { |
| 24 | public: |
Tom Hughes | fc99861 | 2020-08-27 15:52:08 -0700 | [diff] [blame] | 25 | ScopedBN_CTX() : ctx_(BN_CTX_new()) { BN_CTX_start(ctx_); } |
Wei-Cheng Xiao | 174e16f | 2020-02-20 16:12:55 +0800 | [diff] [blame] | 26 | |
| 27 | ~ScopedBN_CTX() { |
| 28 | BN_CTX_end(ctx_); |
| 29 | BN_CTX_free(ctx_); |
| 30 | } |
| 31 | |
| 32 | BN_CTX* get() { return ctx_; } |
| 33 | |
| 34 | private: |
| 35 | BN_CTX* ctx_; |
| 36 | }; |
| 37 | |
| 38 | // Creates and returns a secure random blob with the given |length|. In case of |
| 39 | // an error, returns an empty blob. |
| 40 | HWSEC_EXPORT brillo::SecureBlob CreateSecureRandomBlob(size_t length); |
| 41 | |
| 42 | // Gets the latest OpenSSL error in the following format: |
| 43 | // error:[error code]:[library name]:[function name]:[reason string] |
| 44 | HWSEC_EXPORT std::string GetOpensslError(); |
| 45 | |
Meng-Huan Yu | 4cbaddc | 2019-05-08 18:31:53 +0800 | [diff] [blame] | 46 | // Convert RSA key (with public and/or private key set) key to the binary DER |
| 47 | // encoded SubjectPublicKeyInfo format. |
| 48 | // |
| 49 | // Return nullopt if key is null, or OpenSSL returned error. |
| 50 | HWSEC_EXPORT base::Optional<std::vector<uint8_t>> |
| 51 | RsaKeyToSubjectPublicKeyInfoBytes(const crypto::ScopedRSA& key); |
| 52 | |
| 53 | // Convert ECC key (with public and/or private key set) key to the binary DER |
| 54 | // encoded SubjectPublicKeyInfo format. |
| 55 | // |
| 56 | // Return nullopt if key is null, or OpenSSL returned error. |
| 57 | HWSEC_EXPORT base::Optional<std::vector<uint8_t>> |
| 58 | EccKeyToSubjectPublicKeyInfoBytes(const crypto::ScopedEC_KEY& key); |
| 59 | |
| 60 | } // namespace hwsec |
| 61 | |
| 62 | #endif // LIBHWSEC_CRYPTO_UTILITY_H_ |