blob: d0d89c8523cca04adbf9270c621f3c32b45f6c23 [file] [log] [blame]
Meng-Huan Yu4cbaddc2019-05-08 18:31:53 +08001// 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 Xiao174e16f2020-02-20 16:12:55 +080013#include <brillo/secure_blob.h>
Meng-Huan Yu4cbaddc2019-05-08 18:31:53 +080014#include <crypto/scoped_openssl_types.h>
Wei-Cheng Xiao174e16f2020-02-20 16:12:55 +080015#include <openssl/bn.h>
Meng-Huan Yu4cbaddc2019-05-08 18:31:53 +080016
17#include "libhwsec/hwsec_export.h"
18
19namespace hwsec {
20
Wei-Cheng Xiao174e16f2020-02-20 16:12:55 +080021// RAII version of OpenSSL BN_CTX, with auto-initialization on instantiation and
22// auto-cleanup on leaving scope.
23class HWSEC_EXPORT ScopedBN_CTX {
24 public:
Tom Hughesfc998612020-08-27 15:52:08 -070025 ScopedBN_CTX() : ctx_(BN_CTX_new()) { BN_CTX_start(ctx_); }
Wei-Cheng Xiao174e16f2020-02-20 16:12:55 +080026
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.
40HWSEC_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]
44HWSEC_EXPORT std::string GetOpensslError();
45
Meng-Huan Yu4cbaddc2019-05-08 18:31:53 +080046// 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.
50HWSEC_EXPORT base::Optional<std::vector<uint8_t>>
51RsaKeyToSubjectPublicKeyInfoBytes(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.
57HWSEC_EXPORT base::Optional<std::vector<uint8_t>>
58EccKeyToSubjectPublicKeyInfoBytes(const crypto::ScopedEC_KEY& key);
59
60} // namespace hwsec
61
62#endif // LIBHWSEC_CRYPTO_UTILITY_H_