繁体   English   中英

将证书链添加到C#中的PKCS#7 / CMS容器中

[英]Adding a certificate chain to a PKCS#7/CMS container in C#

我正在从使用的服务中获取PKCS#7 / CMS容器,该容器包括用户证书和签名。

我可以使用SignedCms查看单个证书

var cert = GetCertFromServer();

SignedCms signedCms = new SignedCms();
signedCms.Decode(cert);

// The user certificate
X509Certificate2 userCert = signedCms.Certificates[0];  

但是我需要将中间证书和根证书添加到该链中。 SignedCms.Certificates似乎是不可变的,因此我无法将证书直接添加到集合中,并且无法通过以下方式替换证书集合

// root, inter and leaf certs are X509Certificate2 objects read from files
X509Certificate2[] certArr = new[] {rootCert, interCert, leafCert, userCert};

X509Certificate2Collection chain = new X509Certificate2Collection(certArr);

signedCms.Certificates = chain; // Error: No setter

由于SignedCms.Certificates没有设置程序。 我一直无法找到一种方法来从这个容器中创建一个新容器。 我也没有运气在弹力城堡或任何其他图书馆中找到有关如何执行此操作的信息。

我需要一个包含证书链和签名的容器,并将该容器中的字节写到我正在签名的PDF文件中。 有没有一种方法可以向容器中的链添加证书?

我知道问这个问题已经有好几年了,但是最近我遇到了同样的问题。

对于存在相同问题的任何人, X509Certificate2Collection类都有一个Export方法。

X509Certificate2[] certArr = certificates.ToArray();
X509Certificate2Collection chain = new X509Certificate2Collection(certArr);
byte[] result = chain.Export(X509ContentType.Pkcs7);

.NET Core 3.0已添加SignedCms.AddCertificate 您无法控制排序(SignedCms.Encode()使用DER编码规则写入数据,该规则指示此特定集合首先被最小排序),但是没关系... X509Chain对其进行了整理。

SignedCms signedCms = new SignedCms();
signedCms.Decode(data);

signedCms.AddCertificate(leafCert);
signedCms.AddCertificate(interCert);
signedCms.AddCertificate(rootCert);

byte[] reencoded = signedCms.Encode();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM