Using OpenSSL RSA Key with .Net
OpenSSL offers varying key formats, causing compatibility issues with different modules.
Issue: .Net requires a key in format "-----BEGIN PUBLIC KEY-----", rather than the "-----BEGIN RSA PUBLIC KEY-----" format generated by OpenSSL.
Solution:
Use PEM_write_bio_PUBKEY instead of PEM_write_bio_RSAPublicKey to write the public key. PEM_write_bio_PUBKEY includes the required "SubjectPublicKeyInfo" structure, while PEM_write_bio_RSAPublicKey only outputs the public key.
Converting Keys to the Required Format:
To convert an OpenSSL RSA key to the format required by .Net, you can use the following code:
<code class="cpp">BIO_FILE_ptr pem1(BIO_new_file("rsa-public-1.pem", "w"), ::BIO_free); EVP_KEY_ptr pkey(EVP_PKEY_new(), ::EVP_PKEY_free); rc = RSA_generate_key_ex(rsa.get(), 2048, bn.get(), NULL); ASSERT(rc == 1); rc = EVP_PKEY_set1_RSA(pkey.get(), rsa.get()); ASSERT(rc == 1); rc = PEM_write_bio_PUBKEY(pem1.get(), pkey.get()); ASSERT(rc == 1);</code>
This will create a PEM file named "rsa-public-1.pem" containing the public key in the required format.
Example:
Consider the following example, where the "publicKey" variable holds a key in the format not recognized by .Net:
<code class="cpp">string publicKey = @"-----BEGIN RSA PUBLIC KEY----- ... -----END RSA PUBLIC KEY-----"; CryptoKey key = CryptoKey.FromPublicKey(publicKey, ""); RSA rsa = key.GetRSA();</code>
Replacing "publicKey" with the key generated using the provided code will resolve the exception encountered while trying to create a CryptoKey object.
The above is the detailed content of How to Convert OpenSSL RSA Keys for Use with .Net?. For more information, please follow other related articles on the PHP Chinese website!