Using OpenSSL RSA Keys in .NET
When creating an RSA key pair using OpenSSL RSA_generate_key(), it generates public and private keys in the pkcs#1 format by default. However, .NET expects them to be in the x509 format.
PEM Encoding Formats
A PEM-encoded key can be written using two formats:
.NET Support for Key Formats
.NET supports both ASN.1/DER encoded keys and PEM encoded keys that write the SubjectPublicKeyInfo structure, not just the public key.
Converting to X509 Format
To convert the pkcs#1 public key to x509 format, use PEM_write_bio_PUBKEY instead of PEM_write_bio_RSAPublicKey in your C code. This writes the SubjectPublicKeyInfo structure.
Code Example
<code class="cpp">... // Convert RSA key to PKEY EVP_KEY_ptr pkey(EVP_PKEY_new(), ::EVP_PKEY_free); rc = EVP_PKEY_set1_RSA(pkey.get(), rsa.get()); ASSERT(rc == 1); ... // Write SubjectPublicKeyInfo with OID in PEM // Load with PEM_read_bio_PUBKEY rc = PEM_write_bio_PUBKEY(pem2.get(), pkey.get()); ASSERT(rc == 1); ...</code>
Additional Notes
Related Links
The above is the detailed content of How to Convert OpenSSL RSA Keys to X.509 Format for .NET?. For more information, please follow other related articles on the PHP Chinese website!