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

时间:2021-11-02 13:13:32

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