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


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

2.代碼如下

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); }

以上。

 

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM