1
votes

I try to export pfx file which contain certificates chain and private key from windows certificates store, convert oit into PEM format and save it to file which be read by openssl based application. I do it by the following steps (capi / openssl commands):

creating memory store - CertOpenStore

Open system store - CertOpenSystemStore

find desired certificate according to freindly name - CertFindCertificateInStore

Add desired certificate to memory store - CertAddCertificateContextToStore

export memory store - PFXExportCertStoreEx

convert blob into base64 and save into file

Import certificates chain from PEM file- SSL_CTX_use_certificate_chain_file

Import private key from PEM file - SSL_CTX_use_PrivateKey_file

1) I didn't find a command which convert pfx (memory blob / file) to pem format

2) does this scenario export all certificate chain which were originally store in the pfx file

3) does SSL_CTX_use_certificate_chain_file import all certificates chain or I have to use other commands to import all chain into CTX structure

Thanks in advance

1

1 Answers

0
votes

1) This worked for me

{
    FILE* fp = NULL;
    CString errorS = NULL;
    PKCS12* p12 = NULL;
    EVP_PKEY* pkey = NULL;
    X509* cert = NULL;
    STACK_OF(X509) *ca = NULL;

    int i;
    pkey = (EVP_PKEY*)new EVP_PKEY;
    cert = (X509*)new X509;

    do
    {
        if (fopen_s(&fp, CT2A(pkcs12File), "rb"))
        {
            errorS = ("Error opening file %s\n", CT2A(pkcs12File));
            break;
        }
        p12 = d2i_PKCS12_fp(fp, NULL);
        OpenSSL_add_all_algorithms();
        ERR_load_crypto_strings();
        if (!p12)
        {
            errorS = ("Error reading PKCS#12 file\n");
            break;
        }
        if (!PKCS12_parse(p12, CT2A(szPassword), &pkey, &cert, &ca))
        {
            errorS = ("Error parsing PKCS#12 file\n");
            break;
        }

        if (fopen_s(&fp, CT2A(pszNameString + L".pem"), "w"))
        {
            errorS = ("Error opening file %s\n", CT2A(pemFileName));
            break;
        }
        if (pkey)
        {
            fprintf(fp, "***Private Key***\n");
            PEM_write_PrivateKey(fp, pkey, NULL, NULL, 0, NULL, NULL);
        }
        if (cert)
        {
            fprintf(fp, "***User Certificate***\n");
            PEM_write_X509_AUX(fp, cert);
        }
        if (ca && sk_X509_num(ca))
        {
            fprintf(fp, "***Other Certificates***\n");
            for (i = 0; i < sk_X509_num(ca); i++)
                PEM_write_X509_AUX(fp, sk_X509_value(ca, i));
        }
    } while (0);

        PKCS12_free(p12);
        sk_X509_pop_free(ca, X509_free);
        X509_free(cert);
        EVP_PKEY_free(pkey);

    if (NULL != fp)
    {
        fclose(fp);
    }
}

2+3) SSL_CTX_use_certificate_chain_file import all certificates chain