'Cannot find the requested object' 从字符串创建 X509Certificate2 时出现异常

'Cannot find the requested object' exception while creating X509Certificate2 from string

我正在尝试从字符串创建 X509Certificate2。让我举个例子:

string keyBase64String = Convert.ToBase64String(file.PKCS7);
var cert = new X509Certificate2(Convert.FromBase64String(keyBase64String));

keyBase64String有一个这样的内容:"MIIF0QYJKoZI ........hvcNAQcCoIIFwjCCBb4CA0="

file.PKCS7是我从数据库下载的字节数组

创建 X509Certificate2 时出现以下异常:

Cannot find the requested object

和堆栈跟踪:

"Cannot find requested object" X509Certificate2 Exception "Cannot find requested object"} at System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr) at System.Security.Cryptography.X509Certificates.X509Utils._QueryCertBlobType(Byte[] rawData) at System.Security.Cryptography.X509Certificates.X509Certificate.LoadCertificateFromBlob(Byte[] rawData, Object password, X509KeyStorageFlags keyStorageFlags) at System.Security.Cryptography.X509Certificates.X509Certificate2..ctor(Byte[] rawData) at WebApp.SoupController.d__7.MoveNext() in D:\Projects\WebApp\Controllers\SoupController.cs:line 118

请告诉我我做错了什么。任何帮助将不胜感激!

X509Certificate2 的构造函数期望获得证书文件名,但您给了它一个密钥(X509Certificate2 Constructor (String))

我假设 keyBase64String 是证书密钥,并且证书安装在执行代码的机器上。试试这个:

var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
var certCollection = store.Certificates.Find(X509FindType.FindByThumbprint, keyBase64String , false);
var cert = certCollection[0];

您也可以尝试 FindByKeyUsageFindBySubjectKeyIdentifier 或其他类型的 X509FindType Enumeration

如果 file.PKCS7 表示 PKCS#7 SignedData blob(从 X509Certificate2.Export(X509ContentType.Pkcs7)X509Certificate2Collection.Export(X509ContentType.Pkcs7) 生成的内容),则有两种不同的打开方式:

  • new X509Certificate2(byte[])/new X509Certificate2(string)
    • 单个证书构造函数将提取 SignedData blob 的签名证书。如果这只是作为证书集合导出,但没有签署任何东西,则没有这样的证书,因此失败并显示 Cannot find the original signer.(Win 2012r2,其他版本可以将其映射到不同的字符串)
  • X509Certificate2Collection::Import(byte[])/X509Certificate2Collection::Import(string)
    • 集合导入将消耗所有 "extra" 证书,忽略签名证书。

因此,如果它真的是 PKCS#7,您可能需要集合导入(实例)方法。如果不是,那么您的名字有些奇怪 variable/field/property。