Use OpenSSL RSA key with .Net
Problem:
The .Net framework throws an exception when attempting to use an RSA public key generated with OpenSSL due to a format mismatch. The key is in PKCS#1 format, while .Net expects a X.509 format.
Solution:
Conversion from PKCS#1 to X.509 Format:
To convert the RSA public key from PKCS#1 to X.509 format, use the PEM_write_bio_PUBKEY function instead of PEM_write_bio_RSAPublicKey. This will output the key in the SubjectPublicKeyInfo format with an OID and the public key.
Additionally, you will need to use EVP_PKEY_set1_RSA to convert the RSA key to an EVP_PKEY.
Example Code:
<code class="c++">// Include necessary headers #include <openssl/bn.h> #include <openssl/rsa.h> #include <openssl/pem.h> #include <openssl/bio.h> #include <openssl/x509.h> #include <cassert> #define ASSERT assert using BN_ptr = std::unique_ptr<BIGNUM, decltype(&::BN_free)>; using RSA_ptr = std::unique_ptr<RSA, decltype(&::RSA_free)>; using EVP_KEY_ptr = std::unique_ptr<EVP_PKEY, decltype(&::EVP_PKEY_free)>; using BIO_FILE_ptr = std::unique_ptr<BIO, decltype(&::BIO_free)>; int main(int argc, char* argv[]) { int rc; RSA_ptr rsa(RSA_new(), ::RSA_free); BN_ptr bn(BN_new(), ::BN_free); BIO_FILE_ptr pem1(BIO_new_file("rsa-public-1.pem", "w"), ::BIO_free); BIO_FILE_ptr der1(BIO_new_file("rsa-public-1.der", "w"), ::BIO_free); rc = BN_set_word(bn.get(), RSA_F4); ASSERT(rc == 1); // Generate key rc = RSA_generate_key_ex(rsa.get(), 2048, bn.get(), NULL); ASSERT(rc == 1); // 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 and public key in ASN.1/DER rc = i2d_RSA_PUBKEY_bio(der1.get(), rsa.get()); ASSERT(rc == 1); // Write SubjectPublicKeyInfo with OID and public key in PEM rc = PEM_write_bio_PUBKEY(pem1.get(), pkey.get()); ASSERT(rc == 1); return 0; }</code>
This code generates an RSA key pair and writes the public key in both ASN.1/DER and PEM formats. You can then use the X.509 formatted public key with your .Net application.
The above is the detailed content of How to Use an OpenSSL RSA Key with .NET?. For more information, please follow other related articles on the PHP Chinese website!