c++ - 将 pfx 证书转换为 PEM 格式

标签 c++ openssl x509certificate pem pfx

我发现了这个问题 Converting .PFX to .PEM programmatically? 我有同样的问题,即以编程方式从 Windows keystore 以 pfx 格式导出证书和私钥,并将它们转换为 PEM 格式文件/内存。

上面的链接似乎可以做到,但没有真正的信息是如何完成的,而且指向 github 的内部链接似乎已损坏

我们不能使用 pfx 格式,因为它包含证书链和用于加载此类证书链的 openSSL 库 API 仅适用于 PEM 文件。

当 pfx 文件导入到 Windows keystore 时,私钥被检查为可导出。

我通过将证书复制到新的内存存储成功导出证书,将其导出到内存 bolb 并以不同的格式(base64 和二进制)将其保存到文件中 - 请参见下面的代码 - 但我不确定它是否正确这样做,如果所有链都已导出,我也不知道如何将其转换为 PEM 格式

在此先感谢您的帮助

#pragma comment(lib, "crypt32.lib")

#include <stdio.h>
#include <windows.h>
#include <Wincrypt.h>
#define MY_ENCODING_TYPE  (PKCS_7_ASN_ENCODING | X509_ASN_ENCODING)
void MyHandleError(char *s);

char *base64_encode(const unsigned char *data,
                    size_t input_length,
                    size_t *output_length);

void main(void)
{
//-------------------------------------------------------------------
// Declare and initialize variables.
HCERTSTORE         hSystemStore;
HCERTSTORE         hTempStore;
PCCERT_CONTEXT     pCertContext = NULL;
char pszStoreName[256] = "root";
char               pszNameString[256] = "xyzabcfkjvfkvnrg"; 

//-------------------------------------------------------------------
// Open a system certificate store.
if(hSystemStore = CertOpenSystemStore(
    0,
    pszStoreName))
{
  printf("The %s system store is open. Continue.\n", pszStoreName );
}
else
{
  MyHandleError("The first system store did not open.");
}

//-------------------------------------------------------------------
// Open a temporary certificate store.
if(hTempStore = CertOpenStore(
    CERT_STORE_PROV_MEMORY, 0, 0, CERT_STORE_CREATE_NEW_FLAG, 0 ))
{
  printf("Temp certificate store was created. Continue.\n");
}
else
{
  MyHandleError("The temp store wasn't not created.");
}
//-------------------------------------------------------------------
// Get a certificate that has the desired friendly name. 
if(pCertContext=CertFindCertificateInStore(
      hSystemStore,
      MY_ENCODING_TYPE,             // Use X509_ASN_ENCODING
      0,                            // No dwFlags needed 
      CERT_NAME_FRIENDLY_DISPLAY_TYPE,        // Find a certificate
      pszNameString, // The Unicode string to be found
                                    // in a certificate's subject
      NULL))                        // NULL for the first call 
{
  printf("The %s certificate was found. \n", pszNameString);
}
else
{
   MyHandleError("Could not find the %s certificate.");
}

//------------------------------------------------------------------
// add selected certificate into temporary store in memory

if(CertAddCertificateContextToStore(hTempStore, pCertContext, CERT_STORE_ADD_NEW, 0))
{
  printf("The %s certificate was added. \n", pszNameString);
}
else
{
   MyHandleError("Could not add %s ce


#pragma comment(lib, "crypt32.lib")

#include <stdio.h>
#include <windows.h>
#include <Wincrypt.h>
#define MY_ENCODING_TYPE  (PKCS_7_ASN_ENCODING | X509_ASN_ENCODING)
void MyHandleError(char *s);

char *base64_encode(const unsigned char *data,
                    size_t input_length,
                    size_t *output_length);

void main(void)
{
//-------------------------------------------------------------------
// Declare and initialize variables.
HCERTSTORE         hSystemStore;
HCERTSTORE         hTempStore;
PCCERT_CONTEXT     pCertContext = NULL;
char pszStoreName[256] = "root";
char               pszNameString[256] = "xyzabcfkjvfkvnrg"; 

//-------------------------------------------------------------------
// Open a system certificate store.
if(hSystemStore = CertOpenSystemStore(
    0,
    pszStoreName))
{
  printf("The %s system store is open. Continue.\n", pszStoreName );
}
else
{
  MyHandleError("The first system store did not open.");
}

//-------------------------------------------------------------------
// Open a temporary certificate store.
if(hTempStore = CertOpenStore(
    CERT_STORE_PROV_MEMORY, 0, 0, CERT_STORE_CREATE_NEW_FLAG, 0 ))
{
  printf("Temp certificate store was created. Continue.\n");
}
else
{
  MyHandleError("The temp store wasn't not created.");
}
//-------------------------------------------------------------------
// Get a certificate that has the desired friendly name. 
if(pCertContext=CertFindCertificateInStore(
      hSystemStore,
      MY_ENCODING_TYPE,             // Use X509_ASN_ENCODING
      0,                            // No dwFlags needed 
      CERT_NAME_FRIENDLY_DISPLAY_TYPE,        // Find a certificate
      pszNameString, // The Unicode string to be found
                                    // in a certificate's subject
      NULL))                        // NULL for the first call 
{
  printf("The %s certificate was found. \n", pszNameString);
}
else
{
   MyHandleError("Could not find the %s certificate.");
}

//------------------------------------------------------------------
// add selected certificate into temporary store in memory

if(CertAddCertificateContextToStore(hTempStore, pCertContext, CERT_STORE_ADD_NEW, 0))
{
  printf("The %s certificate was added. \n", pszNameString);
}
else
{
   MyHandleError("Could not add %s certificate.");
}

//------------------------------------------------------------------------------


CRYPT_DATA_BLOB* db= new (CRYPT_DATA_BLOB);
LPCWSTR szPassword = NULL;
db->cbData = 0;

if((!PFXExportCertStoreEx(
                        hTempStore, 
                        db, 
                        szPassword, 
                        0, 
                        EXPORT_PRIVATE_KEYS|REPORT_NOT_ABLE_TO_EXPORT_PRIVATE_KEY))&&(GetLastError()==0))
{
  printf("The %s certificate blob size is %d. \n", pszNameString, db->cbData);
}
else
{
   MyHandleError("Could not calculate size of certificate.");
}

//-------------------------------------------------------
// Allocate memory 
if(db->pbData = (BYTE*)malloc(db->cbData+1))
{
     printf("Memory has been allocated. Continue.\n");
}
else
{
     MyHandleError("The allocation of memory failed.");
}

// Export certificate from temporary store to blob

if(PFXExportCertStoreEx(
                        hTempStore, 
                        db, 
                        szPassword, 
                        0, 
                        EXPORT_PRIVATE_KEYS|REPORT_NOT_ABLE_TO_EXPORT_PRIVATE_KEY))
{
  printf("The %s certificate blob was exported %d. \n", pszNameString);
}
else
{
   MyHandleError("Could not export certificate.");
}


//-------------------------------------------------------------------
//Write blob to files

FILE *fp;
errno_t err;
if ((err = fopen_s(&fp, "cert_bin.p12", "wb")) != 0)
    printf("File was not opened\n");
else
    for (int i=0; i<db->cbData; i++)
    fprintf(fp,"%c", db->pbData + i);
fclose(fp);

size_t t;
char* c = base64_encode(db->pbData, db->cbData, &t);

if ((err = fopen_s(&fp, "cert_base64.p12", "w")) != 0)
    printf("File was not opened\n");
else
    fprintf(fp, "%s", c);
fclose(fp);

//-------------------------------------------------------------------
// Free memory.

//free(pbElement);
CertCloseStore(hSystemStore,0);
printf("The program ran without error to the end.\n");
} // End of main

//-------------------------------------------------------------------
void MyHandleError(char *s)
{
    fprintf(stderr,"An error occurred in running the program. \n");
    fprintf(stderr,"%s\n",s);
    fprintf(stderr, "Error number %x.\n", GetLastError());
    fprintf(stderr, "Program terminating. \n");
    exit(1);
} // End of MyHandleError

最佳答案

此代码段将证书链从 WCS 导出到 pfx 文件

{
    CString errorS = NULL;
    CString  pkcs12File = pszNameString;
    CString szPassword = L"XXXXXXXXX";
    do {
        //-------------------------------------------------------------------
        // Declare and initialize variables.
        HCERTSTORE         hSystemStore = NULL;
        HCERTSTORE         hTempStore = NULL;
        PCCERT_CONTEXT     pCertContext = NULL;

        //-------------------------------------------------------------------
        // Open a system certificate store.
        if (!(hSystemStore = CertOpenSystemStore(
            0,
            (LPCWSTR)pszStoreName)))
        {
            errorS = ("system store did not open.");
            break;
        }

        //-------------------------------------------------------------------
        // Open a temporary certificate store.
        if (!(hTempStore = CertOpenStore(
            CERT_STORE_PROV_MEMORY, 0, 0, CERT_STORE_CREATE_NEW_FLAG, 0)))
        {
            errorS = ("The temp store wasn't created.");
            break;
        }

        //-------------------------------------------------------------------
        // Get a certificate that has the desired friendly name. 
        if (!(pCertContext = CertFindCertificateInStore(
            hSystemStore,
            MY_ENCODING_TYPE,             // Use X509_ASN_ENCODING
            0,                            // No dwFlags needed 
            CERT_FIND_SUBJECT_STR,        // Find a certificate
            pszNameString, // The Unicode string to be found
            // in a certificate's subject
            NULL)))                        // NULL for the first call 
        {
            errorS = ("Could not find the certificate . " + pszNameString);
            break;
        }

            //-------------------------------------------------------------------
            PCCERT_CHAIN_CONTEXT     pChainContext = NULL;
            CERT_CHAIN_PARA          ChainPara;
            DWORD                    dwFlags = 0;
            CERT_ENHKEY_USAGE        EnhkeyUsage;
            CERT_USAGE_MATCH         CertUsage;

            EnhkeyUsage.cUsageIdentifier = 0;
            EnhkeyUsage.rgpszUsageIdentifier = NULL;
            CertUsage.dwType = USAGE_MATCH_TYPE_AND;
            CertUsage.Usage = EnhkeyUsage;
            ChainPara.cbSize = sizeof(CERT_CHAIN_PARA);
            ChainPara.RequestedUsage = CertUsage;

            if (!CertGetCertificateChain(
                NULL,                  // use the default chain engine
                pCertContext,          // pointer to the end certificate
                NULL,                  // use the default time
                NULL,                  // search no additional stores
                &ChainPara,            // use AND logic and enhanced key usage 
                //  as indicated in the ChainPara 
                //  data structure
                dwFlags,
                NULL,                  // currently reserved
                &pChainContext))       // return a pointer to the chain created
            {
                errorS = ("Could not get certificate chain.");
                break;
            }

        //------------------------------------------------------------------
        // add selected certificate into temporary store in memory
            for (int l_chain = 0; l_chain < (int)(pChainContext->cChain); l_chain++)
                for (int l_cert = 0; l_cert < (int)(pChainContext->rgpChain[l_chain]->cElement); l_cert++)
                {           
                    pCertContext = (PCCERT_CONTEXT)pChainContext->rgpChain[l_chain]->rgpElement[l_cert]->pCertContext;
        if (!(CertAddCertificateContextToStore(hTempStore, pCertContext, CERT_STORE_ADD_NEW, 0)))
        {
            errorS = ("Could not add certificate.");
            break;
        }
                }

            CertFreeCertificateChain(pChainContext);

        //------------------------------------------------------------------------------
            // Export certificates chain to memory bolb

        CRYPT_DATA_BLOB* db = new (CRYPT_DATA_BLOB);
            LPCWSTR szPassword = L"XXXXXXXXX";
        db->cbData = 0;

            // calculating required memory space

        if ((PFXExportCertStoreEx(
            hTempStore,
            db,
            szPassword,
            0,
            EXPORT_PRIVATE_KEYS | REPORT_NOT_ABLE_TO_EXPORT_PRIVATE_KEY)) && (GetLastError() == 0))
        {
            errorS = ("Could not calculate size of certificate.");
            break;
        }

        // Allocate memory 
        if (!(db->pbData = (BYTE*)malloc(db->cbData)))
        {
            errorS = ("The allocation of memory failed.");
            break;
        }

        // Export certificate from temporary store to blob

        if (!PFXExportCertStoreEx(
            hTempStore,
            db,
            szPassword,
            0,
            EXPORT_PRIVATE_KEYS | REPORT_NOT_ABLE_TO_EXPORT_PRIVATE_KEY))
        {
            errorS = ("Could not export certificate.");
            break;
        }

        //-------------------------------------------------------------------
        //Write blob to files

        FILE *fp = NULL;
        errno_t err;
        if ((err = fopen_s(&fp, CT2A(pkcs12File), "wb")) != 0)
        {
            errorS = ("File was not opened\n");
            break;
        }
        else
            fwrite(db->pbData, 1, db->cbData, fp);
        fclose(fp);
        //-------------------------------------------------------------------
        // Free memory.

        CertCloseStore(hSystemStore, 0);

        //--------------------------------------------------------------------------

    } while (0);

关于c++ - 将 pfx 证书转换为 PEM 格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45164665/

相关文章:

c++ - 如何在 C++ 中使用 X509 证书模数在 token 中查找私钥

linux - 服务器 linux - 无法初始化 OpenSSL 库

encryption - 证书签名请求中手动创建的签名与 openssl req 生成的签名不匹配

ssl - 错误 : failed to find any PEM data in certificate input when start to run fleet server

c# - X509Certificate.CreateFromCertFile - 指定的网络密码不正确

c++ - OpenGL - 简单 3d 游戏的低 FPS

c++ - 使用带有 soci::indicators [C++] 的 SOCI 从表中获取行

visual-studio-2008 - 带有 OpenSSL 的 Axis2C - 没有 OPENSSL_APPLINK 错误

flutter - 如何在Dart中创建证书(X509Certificate)?

c++ - 为返回 C++/.NET 老手学习 Boost 的最快方法