You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C# Compact Framework 3.5中导入多个X509证书?

问题描述

在C# Compact Framework 3.5 + Windows CE环境下,需导入多个X509证书,但现有System.Security.Cryptography.X509Certificates类库仅支持单证书导入,且新版C#的X509CertificatesCollection在该CF版本中不可用,需实现多证书导入的方法及参考方案。

可行实现方案

通过逆向实现类似X509CertificateCollection的功能,利用X509Certificate2Collection完成多证书导入与拆分,具体代码如下:

using System.Security.Cryptography.X509Certificates;
using System.IO;
using System.Collections.Generic;

class MyProgram
{
    static void Main(string[] args)
    {
        string fileName = "c:\\cert\\file_0.cer";
        string password = "Labuser1";
        bool result = isSingleCertificate(fileName, password);
        ParseMultipleCertificates(fileName, password);
    }

    static bool isSingleCertificate(string path, string password)
    {
        bool isSingle;
        X509Certificate2Collection collection = new X509Certificate2Collection();
        collection.Import(path, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
        isSingle = collection.Count == 1;
        return isSingle;
    }

    static List<string> ParseMultipleCertificates(string path, string password)
    {
        X509Certificate2Collection collection = new X509Certificate2Collection();
        collection.Import(path, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
        List<string> filePathList = new List<string>();
        int inc = 0;

        foreach (X509Certificate2 cert in collection)
        {
            inc++;
            string filename = $"c:\\cert\\temp\\file_{inc}.cer";
            filePathList.Add(filename);
            byte[] myArray;
            
            if (!string.IsNullOrEmpty(password))
                myArray = cert.Export(X509ContentType.Cert, password);
            else
                myArray = cert.Export(X509ContentType.Cert);

            using (FileStream fileStream = new FileStream(filename, FileMode.Create))
            {
                fileStream.Write(myArray, 0, myArray.Length);
            }
        }
        return filePathList;
    }
}

代码说明

  • isSingleCertificate:验证目标证书文件是否仅包含单证书,通过导入后集合的元素数量判断。
  • ParseMultipleCertificates:导入多证书文件,遍历集合内的每个证书,将其导出为单独的.cer文件,最终返回所有拆分后证书的路径列表。

内容的提问来源于stack exchange,提问作者T P

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 03:10:16