首页 > 编程语言 > 详细

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

时间:2019-06-17 20:07:44      阅读:157      评论:0      收藏:0      [点我收藏+]

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文件

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

原文:https://www.cnblogs.com/chevin/p/11041480.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!