2009-02-19 21 views
49

我有通过MakeCert生成的证书。我想使用此证书来使用PeerTrust进行WCF消息安全。如何以编程方式将证书安装到使用c#或.NET的“可信任人员”本地机器证书存储区中?如何使用c#以编程方式将证书安装到本地机器存储中?

我有一个CER文件,但也可以创建一个PFX。

+0

顺便说一句 - 我知道Makecert和信任的细节。请仅仅寻求使用编程的c#或installshield安装证书的建议。谢谢! – 2009-02-19 18:38:22

+0

任何想法如何在C程序中做到这一点?在Windows中的任何API? – 2vision2 2012-05-24 05:01:13

回答

53

我相信这是正确的:

using (X509Store store = new X509Store(StoreName.TrustedPeople, StoreLocation.LocalMachine)) 
{ 
    store.Open(OpenFlags.ReadWrite); 
    store.Add(cert); //where cert is an X509Certificate object 
} 
+1

这安装证书成功,但是当我打开个人存储中的私钥的管理私钥选项时,它会给出“找不到证书的密钥”错误。 – mit 2016-12-08 10:34:00

35

以下工作对我好:

private static void InstallCertificate(string cerFileName) 
{ 
    X509Certificate2 certificate = new X509Certificate2(cerFileName); 
    X509Store store = new X509Store(StoreName.TrustedPublisher, StoreLocation.LocalMachine); 

    store.Open(OpenFlags.ReadWrite); 
    store.Add(certificate); 
    store.Close(); 
} 
6

,而不是安装证书LOCALMACHINE需要提升权限,你可以将它添加到“当前用户“(为我工作)。

X509Store store = new X509Store(StoreName.TrustedPeople, StoreLocation.CurrentUser); 
store.Open(OpenFlags.ReadWrite); 
store.Add(cert); //where cert is an X509Certificate object 
store.Close(); 
相关问题