7#include <openssl/evp.h>
19 EVP_PKEY*
key =
nullptr;
27 key = PEM_read_bio_PUBKEY(mem,
nullptr,
nullptr,
nullptr);
30 throw std::runtime_error(
"could not parse PEM");
37 key = d2i_PUBKEY_bio(buf, &
key);
40 throw std::runtime_error(
"Could not read DER");
48 throw std::logic_error(
"Public key is not initialized");
51 const int key_type = EVP_PKEY_get_base_id(
key);
53 if (key_type == EVP_PKEY_EC)
58 std::string gname(gname_len + 1,
'\0');
60 EVP_PKEY_get_group_name(
key, gname.data(), gname.size(), &gname_len));
61 gname.resize(gname_len);
64 if (gname == SN_X9_62_prime256v1)
68 throw std::domain_error(fmt::format(
69 "secp256r1 key cannot be used with COSE algorithm {}", cose_alg));
72 else if (gname == SN_secp384r1)
76 throw std::domain_error(fmt::format(
77 "secp384r1 key cannot be used with COSE algorithm {}", cose_alg));
80 else if (gname == SN_secp521r1)
84 throw std::domain_error(fmt::format(
85 "secp521r1 key cannot be used with COSE algorithm {}", cose_alg));
90 throw std::domain_error(
91 fmt::format(
"Unsupported EC curve: {}", gname));
94 else if (key_type == EVP_PKEY_RSA || key_type == EVP_PKEY_RSA_PSS)
101 if (cose_alg != -37 && cose_alg != -38 && cose_alg != -39)
103 throw std::domain_error(
104 fmt::format(
"Incompatible cose algorithm {} for RSA", cose_alg));
109 throw std::domain_error(
110 fmt::format(
"Unsupported key type {}", key_type));
114 operator EVP_PKEY*()
const
123 BUF_MEM* bptr =
nullptr;
124 BIO_get_mem_ptr(buf, &bptr);
125 return {bptr->data, bptr->data + bptr->length};
Definition public_key.h:14
PublicKey_OpenSSL()=default
PublicKey_OpenSSL(const Pem &pem)
Definition public_key.h:24
virtual ~PublicKey_OpenSSL()
Definition public_key.h:128
void check_is_cose_compatible(int cose_alg)
Definition public_key.h:44
PublicKey_OpenSSL(EVP_PKEY *key)
Definition public_key.h:23
PublicKey_OpenSSL(std::span< const uint8_t > der)
Definition public_key.h:34
std::vector< uint8_t > public_key_der() const
Definition public_key.h:119
EVP_PKEY * key
Definition public_key.h:19
void CHECK1(int rc)
Throws if rc is not 1.
Definition openssl_wrappers.h:54
Definition openssl_wrappers.h:150