【问题标题】:How Can I Combine Multiple .p12 Certificates Into One .pfx file如何将多个 .p12 证书合并到一个 .pfx 文件中
【发布时间】:2016-09-19 02:42:24
【问题描述】:

我有大量单个证书存储为扩展名为 .p12 的文件。我想将所有这些证书合并到一个 .pfx 文件中,以减少在客户端计算机上导入所有这些证书的工作量。 这是我尝试过的。它会创建文件,但是当我导入 .pfx 文件时会出现问题。 Windows 证书导入向导仅导入第一个证书并忽略之后的所有内容。我认为是因为我尝试将它们组合在一起的方式导致文件格式有问题。我不确定这样做的正确方法。有任何想法吗?

private void btnCombineCerts_Click(object sender, EventArgs e)
{
    String dateString = DateTime.Now.ToString("yyyyMMdd");
    String timeString = DateTime.Now.ToString("hhmmssff");
    String path = Directory.GetCurrentDirectory() + @"\certs\CombinedCerts\";
    if (!Directory.Exists(path))
    {
        Directory.CreateDirectory(path);
    }
    List<X509Certificate2> certs = new List<X509Certificate2>();
    foreach(var certFile in fDialog.FileNames)
    {
        X509Certificate2 cert = new X509Certificate2(certFile);
        certs.Add(cert);
    }
    foreach(X509Certificate2 cert in certs)
    {                
        byte[] certStream = cert.Export(X509ContentType.Pfx);
        using (var stream = new FileStream(path + dateString + "CombinedCerts" + timeString + ".pfx", FileMode.Append))
        {
            stream.Write(certStream, 0, certStream.Length);
        }

    }
}

【问题讨论】:

    标签: c# certificate x509certificate2


    【解决方案1】:

    PFX 本质上支持多个证书,但它不像您编写的那样是一个顺序文件。我不知道 UI 是否会正确导入它,但如果所有内容都有私钥,它可能会正确导入。 X509Certificate2Collection 的一个真正用途是它可以导出或导入。

    var certs = new X509Certificate2Collection();
    
    foreach (var certFile in fDialog.FileNames)
    {
        certs.Add(new X509Certificate2(certFile));
    }
    
    byte[] oneBigPfx = certs.Export(X509ContentType.Pfx);
    File.WriteAllBytes(filename, oneBigPfx);
    

    【讨论】:

    • 这非常有效。谢谢你。我还要提到 Export 方法采用密码参数,这是一个额外的好处。
    • 就我而言,为两个证书运行上述代码时,我收到了(德语)错误消息System.Security.Cryptography.CryptographicException: Schlüssel ist im angegebenen Status nicht gültig.。翻译成Key not valid for use in specified state.。看来你have to specify the "Exportable" enum flag in the c'tor 是为了避免错误。甚至适用于没有密码的证书;只需指定一个空字符串即可。
    【解决方案2】:
    public X509Certificate2 Merge(List<X509Certificate2> certificates)
    {
        var certs = new X509Certificate2Collection();
    
        foreach (var certFile in certificates)
        {
            certs.Add(new X509Certificate2(certFile));
        }
    
        byte[] data = certs.Export(X509ContentType.Pfx);
    
        X509Certificate2 newFile = new X509Certificate2(data);
    
        return newFile;
    }
    

    【讨论】:

      猜你喜欢
      • 2013-09-18
      • 2018-05-27
      • 2022-07-11
      • 2019-12-09
      • 2016-07-08
      • 2021-09-11
      • 1970-01-01
      • 2013-05-25
      • 1970-01-01
      相关资源
      最近更新 更多