C++ OpenSSL 之二:生成RSA文件

1.等同於生成private key: openssl genrsa -out "save_path" 2048html

2.代碼以下spa

bool MakeRsaKeySSL(const char *savePrivateKeyFilePath, const  char *savePublicKeyFilePath) { int             ret = 0; RSA *r = NULL; BIGNUM *bne = NULL; BIO *bp_public = NULL, *bp_private = NULL; int             bits = 2048; unsigned long   e = RSA_F4; // 1. generate rsa key
    bne = BN_new(); ret = BN_set_word(bne, e); if (ret != 1) { fprintf(stderr, "MakeLocalKeySSL BN_set_word err \n"); goto free_all; } r = RSA_new(); ret = RSA_generate_key_ex(r, bits, bne, NULL); if (ret != 1) { fprintf(stderr, "MakeLocalKeySSL RSA_generate_key_ex err \n"); goto free_all; } // 2. save public key
    if (savePublicKeyFilePath != NULL) { bp_public = BIO_new_file(savePublicKeyFilePath, "w+"); ret = PEM_write_bio_RSAPublicKey(bp_public, r); if (ret != 1) { fprintf(stderr, "MakeLocalKeySSL PEM_write_bio_RSAPublicKey err \n"); goto free_all; } } // 3. save private key
    if (savePrivateKeyFilePath != NULL) { bp_private = BIO_new_file(savePrivateKeyFilePath, "w+"); ret = PEM_write_bio_RSAPrivateKey(bp_private, r, NULL, NULL, 0, NULL, NULL); } // 4. free
free_all: BIO_free_all(bp_public); BIO_free_all(bp_private); RSA_free(r); BN_free(bne); return (ret == 1); }

以上。code

 

《C++ OpenSSL 之一:編譯和使用》
《C++ OpenSSL 之二:生成RSA文件》
《C++ OpenSSL 之三:生成CSR文件》
《C++ OpenSSL 之四:CER轉換爲PEM》
《C++ OpenSSL 之五:生成P12文件
htm

相關文章
相關標籤/搜索