I'm new to OpenSSL and cryptography in general, and I've been stuck at this for a few hours. I have an x5c certificate chain from here (https://login.microsoftonline.com/common/discovery/keys) and I'm trying to convert it to a public key so that I can validate a JWT token (in C++).
I was able to do it on the command line by pasting the x5c certificate with a "-----BEGIN CERTIFICATE------" and end certificate before and after the certificate and calling
openssl x509 -in cert -pubkey -noout > public-key
where cert is "-----BEGIN CERTIFICATE----- MIIDBTCCAe2gAwIBAgIQdEMOjSqDVbdN3mzb2IumCzANBgkqhkiG9w0BAQsFADAt MSswKQYDVQQDEyJhY2NvdW50cy5hY2Nlc3Njb250cm9sLndpbmRvd3MubmV0MB4X DTE5MDYwNDAwMDAwMFoXDTIxMDYwNDAwMDAwMFowLTErMCkGA1UEAxMiYWNjb3Vu dHMuYWNjZXNzY29udHJvbC53aW5kb3dzLm5ldDCCASIwDQYJKoZIhvcNAQEBBQAD ggEPADCCAQoCggEBAKEUUBvom99MdPXlrQ6S9MFmoQPoYI3NJVqEFOJcARY11dj3 zyJogL8MTsTRt+DIJ8NyvYbgWC7K7zkAGzHQZhPJcM/AxSjFqh6qB98UqgxoSGBa G0A4lUZJHnKW3qx+YaiWrkg+z4sAwUkP0QgyI29Ejpkk6WUfe1rOJNc/defFUX+A VGxo81beLVAM/8tnCOSbF0H3IADwd76D/Hrp8RsGf4jPHr8N4VDsO/p7oj8rbOx0 pL1ehjMK13zspmP8NO5mMcP9i5yiJ37FgbXESAxvja7I9t+y4LQYSu05M7la4Lqv //m5A8MBd6k0VxgF/Sq8GOIbkcQ0bJTCIN9B6oMCAwEAAaMhMB8wHQYDVR0OBBYE FNRP0Lf6MDeL11RDH0uL7H+/JqtLMA0GCSqGSIb3DQEBCwUAA4IBAQCJKR1nxp9I j/yisCmDG7bdN1yHj/2HdVvyLfCCyReRfkB3cnTZVaIOBy5occGkdmsYJ+q8uqcz koCMAz3gvvq1c0msKEiNpqWNeU2aRXqyL3QZJ/GBmUK1I0tINPVv8j7znm0DcvHH XFvhzS8E4s8ai8vQkcpyac/7Z4PN43HtjDnkZo9Zxm7JahHshrhA8sSPvsuC4dQA cHbOrLbHG+HIo3Tq2pNl7mfQ9fVJ2FxbqlzPYr/rK8H2GTA6N55SuP3KTNvyL3Rn Ma3hXmGTdG1dpMFzD/IE623h/BqY6j29PyQC/+MUD4UCZ6KW9oIzpi27pKQagH1i 1jpBU/ceH6AW -----END CERTIFICATE-----"
I've been trying to do this in C++ with the following:
BIO *b = BIO_new(BIO_s_mem());
BIO_puts(b, cert); //cert is a byte array with the certificate contents from above
X509 * x509 = PEM_read_bio_X509(b, NULL, NULL, NULL);
EVP_PKEY *pkey = X509_get_pubkey(x509);
auto eckey = EVP_PKEY_get1_EC_KEY(pkey);
auto ecpoint = EC_KEY_get0_public_key(eckey);
size_t public_key_hex_size;
unsigned char* public_key_oct;
EC_GROUP *ec_group = NULL;
ec_group = EC_GROUP_new_by_curve_name(NID_secp521r1);
BN_CTX *bn_ctx = BN_CTX_new();
public_key_hex_size = EC_POINT_point2oct(ec_group, ecpoint, POINT_CONVERSION_COMPRESSED, NULL, 0, bn_ctx);
public_key_oct = (unsigned char *)OPENSSL_malloc(public_key_hex_size);
But then it says x509 is null, so I'm not sure how to correctly read it in from a byte array.
n
) and exponent (e
) keys.x5c
is an optional key in JWK. – identigral