首页 > 编程语言 > 详细

C++ OpenSSL 之五:生成P12文件

时间:2019-06-17 20:48:41      阅读:210      评论:0      收藏:0      [点我收藏+]

1.等同于使用: openssl pkcs12 -export -inkey "key_path" -in "pem_path" -out "save_path" -passout pass:password

2.代码如下:keyFilePath为RSA private key文件。

bool MakeP12SSL(const char* keyFilePath, const char* pemFilePath, const char* pwd, const char* saveP12FilePath) {
    int ret = 0;
    FILE *p12File = NULL;
    EVP_PKEY *pKey = NULL;
    X509 *cert = NULL;
    PKCS12 *p12 = NULL;
    BIO *keyFileBIO = NULL, *pemFileBIO = NULL;
    RSA  *r = NULL;

    keyFileBIO = BIO_new_file(keyFilePath, "r");
    if (keyFileBIO == NULL) {
        fprintf(stderr, "MakeP12SSL BIO_new_file err %s\n", keyFilePath);
        goto free_all;
    }

    r = PEM_read_bio_RSAPrivateKey(keyFileBIO, NULL, NULL, NULL);
    if (r == NULL) {
        fprintf(stderr, "MakeP12SSL PEM_read_bio_RSAPrivateKey err\n");
        goto free_all;
    }

    pKey = EVP_PKEY_new();
    EVP_PKEY_assign_RSA(pKey, r);
    r = NULL;   // will be free rsa when EVP_PKEY_free(pKey)

    pemFileBIO = BIO_new_file(pemFilePath, "r");
    if (pemFileBIO == NULL) {
        fprintf(stderr, "MakeP12SSL BIO_new_file err %s\n", pemFilePath);
        goto free_all;
    }

    cert = PEM_read_bio_X509(pemFileBIO, NULL, NULL, NULL);
    if (cert == NULL) {
        fprintf(stderr, "MakeP12SSL PEM_read_bio_X509 err\n");
        goto free_all;
    }

    p12 = PKCS12_create(pwd, "", pKey, cert, NULL, 0, 0, 0, 0, 0);
    if (p12 == NULL) {
        fprintf(stderr, "MakeP12SSL PKCS12_create err\n");
        goto free_all;
    }

    p12File = fopen(saveP12FilePath, "w+");
    if (p12File == NULL) {
        fprintf(stderr, "MakeP12SSL fopen err %s\n", saveP12FilePath);
        goto free_all;
    }

    ret = i2d_PKCS12_fp(p12File, p12);
    if (ret != 1) {
        fprintf(stderr, "MakeP12SSL i2d_PKCS12_fp err\n");
        goto free_all;
    }

free_all:
    BIO_free_all(keyFileBIO);
    BIO_free_all(pemFileBIO);
    EVP_PKEY_free(pKey);
    PKCS12_free(p12);
    if (p12File) fclose(p12File);

    return (ret == 1);
}

以上。

 

《C++ OpenSSL 之一:编译和使用》
《C++ OpenSSL 之二:生成RSA文件》
《C++ OpenSSL 之三:生成CSR文件》
《C++ OpenSSL 之四:CER转换为PEM》
《C++ OpenSSL 之五:生成P12文件

C++ OpenSSL 之五:生成P12文件

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

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