zoukankan      html  css  js  c++  java
  • C++ OpenSSL 之五:生成P12文件

    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
    ", keyFilePath);
            goto free_all;
        }
    
        r = PEM_read_bio_RSAPrivateKey(keyFileBIO, NULL, NULL, NULL);
        if (r == NULL) {
            fprintf(stderr, "MakeP12SSL PEM_read_bio_RSAPrivateKey err
    ");
            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
    ", pemFilePath);
            goto free_all;
        }
    
        cert = PEM_read_bio_X509(pemFileBIO, NULL, NULL, NULL);
        if (cert == NULL) {
            fprintf(stderr, "MakeP12SSL PEM_read_bio_X509 err
    ");
            goto free_all;
        }
    
        p12 = PKCS12_create(pwd, "", pKey, cert, NULL, 0, 0, 0, 0, 0);
        if (p12 == NULL) {
            fprintf(stderr, "MakeP12SSL PKCS12_create err
    ");
            goto free_all;
        }
    
        p12File = fopen(saveP12FilePath, "w+");
        if (p12File == NULL) {
            fprintf(stderr, "MakeP12SSL fopen err %s
    ", saveP12FilePath);
            goto free_all;
        }
    
        ret = i2d_PKCS12_fp(p12File, p12);
        if (ret != 1) {
            fprintf(stderr, "MakeP12SSL i2d_PKCS12_fp err
    ");
            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文件

  • 相关阅读:
    [非专业翻译] Mapster
    [非专业翻译] Mapster
    排序之猴子算法
    1309游客统计
    1631低洼地
    1636车牌问题
    1638图形
    这是一篇小短文
    1500【自定义函数】走楼梯
    PHP 之表单提交大数据,数据不完整
  • 原文地址:https://www.cnblogs.com/chevin/p/11041852.html
Copyright © 2011-2022 走看看