在 .Net 中使用 OpenSSL RSA 密钥
使用 RSA_generate_key() 生成公钥-私钥对时,OpenSSL 在以下位置输出公钥:以下格式:
-----BEGIN RSA PUBLIC KEY----- ... -----END RSA PUBLIC KEY-----
但是,.Net 中的某些模块需要以下键此格式:
-----BEGIN PUBLIC KEY----- ... -----END PUBLIC KEY-----
要将密钥转换为所需格式,请使用 PEM_write_bio_PUBKEY 而不是 PEM_write_bio_RSAPublicKey。前者写入SubjectPublicKeyInfo,包括OID和公钥。
要转换密钥,请按照以下步骤操作:
C 示例
以下 C 程序演示了转换:
<code class="cpp">#include <memory> #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 pem2(BIO_new_file("rsa-public-2.pem", "w"), ::BIO_free); BIO_FILE_ptr der1(BIO_new_file("rsa-public-1.der", "w"), ::BIO_free); BIO_FILE_ptr der2(BIO_new_file("rsa-public-2.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 just the public key in ASN.1/DER // Load with d2i_RSAPublicKey_bio rc = i2d_RSAPublicKey_bio(der1.get(), rsa.get()); ASSERT(rc == 1); // Write just the public key in PEM // Load with PEM_read_bio_RSAPublicKey rc = PEM_write_bio_RSAPublicKey(pem1.get(), rsa.get()); ASSERT(rc == 1); // Write SubjectPublicKeyInfo with OID and public key in ASN.1/DER // Load with d2i_RSA_PUBKEY_bio rc = i2d_RSA_PUBKEY_bio(der2.get(), rsa.get()); ASSERT(rc == 1); // Write SubjectPublicKeyInfo with OID and public key in PEM // Load with PEM_read_bio_PUBKEY rc = PEM_write_bio_PUBKEY(pem2.get(), pkey.get()); ASSERT(rc == 1); return 0; }</code>
以上是如何将 OpenSSL RSA 公钥转换为 .Net 兼容格式?的详细内容。更多信息请关注PHP中文网其他相关文章!