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

  • 相关阅读:
    装饰器
    函数的初识
    python的文件操作
    深浅copy
    set集合,是一个无序且不重复的元素集合
    基础数据类型 :字典
    列表的增删改查
    易错点 默认参数陷阱
    js中Array对象常用方法
    printf用法demo
  • 原文地址:https://www.cnblogs.com/chevin/p/11041852.html
Copyright © 2011-2022 走看看