将证书添加到x509Store中没有任何作用 C#

5

我正在尝试添加证书,但添加功能似乎没有任何作用。

我有两个证书。 我可以通过右键单击并保存到个人“testStore”存储库来手动添加它们,但是当我尝试以编程方式添加它们时,它们不会被保存。 即使我只添加其中一个证书,X509Store对象也按预期包含它,但是当我调用.Add(cert)时,什么也没有保存。

//I've already added 1 cert manually
X509Certificate2 cert2 = new X509Certificate2(@"C:\temp\Cert2.cer");
X509Store store = new X509Store("testStore", StoreLocation.CurrentUser);
store.Open(OpenFlags.MaxAllowed);

//here store.Certificates has the one Certificate I added manually as expected.

store.Certificates.Add(cert2);

//here store.Certificates still only has the first certificate, cert2 still isn't there..

store.Close();

我有什么遗漏吗?

编辑 我也尝试使用StorePermission(如下),并尝试模拟管理员帐户,但这些都没有帮助。

StorePermission sp = new StorePermission( PermissionState.Unrestricted);
sp.Flags = StorePermissionFlags.AllFlags;
sp.Assert();
2个回答

7

我明白了... 原来应该使用 store.Add() 而不是 store.Certificates.Insert();

//When LocalMachine is used, .Add() requires that you run the app as an administrator in order to work.
X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
X509Certificate2 cert = new X509Certificate2("C:\\test\\test.cer");
store.Open(OpenFlags.MaxAllowed);
store.Add(cert);
store.Close();


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接