views:

2108

answers:

3

Here is the code to add a pfx to the Cert store.

X509Store store = new X509Store( StoreName.My, StoreLocation.LocalMachine );
store.Open( OpenFlags.ReadWrite );
X509Certificate2 cert = new X509Certificate2( "test.pfx", "password" );
store.Add( cert );
store.Close();

However, I couldn't find a way to set permission for NetworkService to access the private key.

Can anyone shed some light? Thanks in advance.

+3  A: 

You can use the WinHttpCertCfg.exe tool that ships as part of the Windows Server 2003 Resource Kit Tools.

Example:

winhttpcertcfg -g -c LOCAL_MACHINE\My -s test -a NetworkService


Alternatively, you could use the Find Private Key tool that ships with the WCF SDK, to find the location on disk of the certificate's private key file. Then you can simply use ACL to set the right privileges on the file.

Example:

FindPrivateKey My LocalMachine -n "CN=test"
Enrico Campidoglio
Thanks, winhttpcertcfg is quite good way of doing it.
codemeit
+3  A: 

To do it programmatically, you have to do three things:

  1. Get the path of the private key folder.

  2. Get the file name of the private key within that folder.

  3. Add the permission to that file.

See this post for some example code that does all three (specifically look at the "AddAccessToCertificate" method).

Eric Rosenberger
Thanks, I like the codeproject one.
codemeit
A: 

Thanks Enrico Campidoglio, Your solution works!!!

Alich
Glad to hear it :-)
Enrico Campidoglio