Home >Backend Development >C++ >How to Convert RSA Keys from PKCS#1 to X.509 Format in OpenSSL?
Converting RSA Keys from PKCS#1 to X.509 Format
In OpenSSL, RSA keys can be saved in two formats:
.NET can handle both ASN.1/DER-encoded keys (PKCS#1) and PEM-encoded keys (X.509). To convert a PKCS#1 key to an X.509 key:
1. Use PEM_write_bio_PUBKEY instead of PEM_write_bio_RSAPublicKey:
2. Convert RSA key to EVP_PKEY using EVP_PKEY_set1_RSA:
Example Code:
<code class="c++">#include <openssl/pem.h> #include <openssl/rsa.h> #include <openssl/evp.h> int main() { RSA *rsa = RSA_new(); BN_set_word(BN_new(), RSA_F4); RSA_generate_key_ex(rsa, 2048, NULL, NULL); EVP_PKEY *pkey = EVP_PKEY_new(); EVP_PKEY_set1_RSA(pkey, rsa); BIO *pem = BIO_new_file("rsa-public.pem", "w"); PEM_write_bio_PUBKEY(pem, pkey); RSA_free(rsa); EVP_PKEY_free(pkey); return 0; }</code>
This program generates an RSA key pair, converts the public key to an X.509 format, and saves it in the "rsa-public.pem" file.
The above is the detailed content of How to Convert RSA Keys from PKCS#1 to X.509 Format in OpenSSL?. For more information, please follow other related articles on the PHP Chinese website!