如何在“企业信任”商店中写信?

时间:2019-01-07 15:16:06

标签: c# .net bouncycastle x509certificate x509certificate2

我有一个带有一些证书的.p7b文件,我想将它们安装在“企业信任”商店中。我要使用的程序希望在那里。

我在C#中有书面代码,可以从文件中提取所有证书,并将它们安装到可以正常工作的X509Store(“ Storename.My”)中。

如果我尝试使用相同的代码在不同的商店(已经存在)中进行写入,则会创建一个新的空商店并在其中进行写入。

StoreName.My来自system.Security.Cryptography.X509证书公共枚举StoreName,但是“企业信任”存储没有选项。 因此,我尝试使用构造函数,在该构造函数中,我可以将StoreName用作字符串。

我从Windows使用certmgr来检查哪些证书存储在哪些商店中。

// open file
var certificateStore = new CmsSignedData(new 
FileStream(_tempFileName.ToString(), FileMode.Open));

// get all certificats
IX509Store x509Certs = certificateStore.GetCertificates("Collection");
var a = new ArrayList(x509Certs.GetMatches(null));

// this works
var store = new X509Store(StoreName.My, StoreLocation.CurrentUser); 

// this doesnt work
// var store = new X509Store("Enterprise Trust", StoreLocation.CurrentUser);

// open store
store.Open(OpenFlags.ReadWrite);

// write in store
foreach (object o in a) {
    var cert = (Org.BouncyCastle.X509.X509Certificate)o;
    var cert509 = new X509Certificate2();
    cert509.Import(cert.GetEncoded());
    store.Add(cert509);
}
store.Close();

如何在不是StoreName枚举的商店中正确书写?

1 个答案:

答案 0 :(得分:0)

如果要确保您没有创建新商店,可以使用OpenFlags值tbody。声明该标志并进行检查,例如OpenExistingOnly产生"Trust2",因此,通过将System.Security.Cryptography.CryptographicException: The system cannot find the file specified.指定为:

,可以最好地确保"Trust"是正确的答案
using (X509Store store = new X509Store("Trust", StoreLocation.CurrentUser))
{
    store.Open(OpenFlags.ReadWrite | OpenFlags.OpenExistingOnly);
    ...
}

(请注意,这在Linux(.NET Core)上使用不太好,因为只有Windows会预先初始化存储)

我们可以通过certutil.exe命令行实用工具来确认程序名称与显示名称的确认:

>certutil -store trust
trust "Enterprise Trust"
CertUtil: -store command completed successfully.

(我只是那家商店什么都没有)