在.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中文網其他相關文章!