如何从 C# 中的文件/流读取 Pkcs#7 证书链?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/579035/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 09:04:29  来源:igfitidea点击:

How to read Pkcs#7 certificate chain from file/stream in C#?

c#x509certificate2pkcs#7

提问by froh42

I have two certificates that I saved to disk. One is a certificate with private key that I exported as a .pfx file, the other one is a certificate that I saved including its certificate chain as a PKCS#7 file ("certchain.p7b").

我有两个保存到磁盘的证书。一个是我导出为 .pfx 文件的带有私钥的证书,另一个是我保存的证书,包括其证书链作为 PKCS#7 文件(“certchain.p7b”)。

In C# I can now load the .pfx file with

在 C# 中,我现在可以加载 .pfx 文件

  var cert = new X509Certificate2(myPfxFileStream); 

(myPfxFileStream is a FileStreamopened to the .pfx File for reading), however trying the same thing with the PKCs#7 Certificate fails in a CryptoGraphicException"Der Indexwert ist ungültig" which translates to "invalid index value".

(myPfxFileStream 是一个FileStream打开的 .pfx 文件以供读取),但是在CryptoGraphicException“Der Indexwert ist ungültig”中尝试使用 PKCs#7 证书尝试相同的操作失败,这会转换为“无效的索引值”。

I assume I have to parse PKCS#7 differently (it contains a chain, not a single certificate!), but how?

我假设我必须以不同的方式解析 PKCS#7(它包含一个链,而不是一个证书!),但是如何解析?

(Oh, by the way: Currently I have no passwords on those certficiates)

(哦,顺便说一句:目前我没有这些证书的密码)

采纳答案by casperOne

You will want to use the SignedCmsclass in the System.Security.Cryptography.Pkcsnamespace.

您将要使用命名空间中的SignedCmsSystem.Security.Cryptography.Pkcs

This blog entry will show you how to use the class:

此博客条目将向您展示如何使用该类:

http://blogs.msdn.com/shawnfa/archive/2006/02/27/539990.aspx

http://blogs.msdn.com/shawnfa/archive/2006/02/27/539990.aspx

You basically will call the Decodemethod, passing the bytes representing the PKCS file.

您基本上将调用该Decode方法,传递代表 PKCS 文件的字节。