Home > Backend Development > C++ > How to Convert RSA Keys from PKCS#1 to X.509 Format in OpenSSL?

How to Convert RSA Keys from PKCS#1 to X.509 Format in OpenSSL?

DDD
Release: 2024-11-07 20:14:03
Original
406 people have browsed it

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:

  • PKCS#1: Only contains the public key.
  • X.509: Includes the SubjectPublicKeyInfo structure, which contains the algorithm OID and the public key.

.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:

  • PEM_write_bio_RSAPublicKey writes only the public key (PKCS#1).
  • PEM_write_bio_PUBKEY writes the SubjectPublicKeyInfo (X.509).

2. Convert RSA key to EVP_PKEY using EVP_PKEY_set1_RSA:

  • This function converts the RSA key to an EVP_PKEY, which includes the algorithm OID.

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template