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.
Right-click the certificate, and select All Tasks > Manage Private Keys. Add the NETWORK SERVICE user to the list of groups and user names. Select the NETWORK SERVICE user and grant it Full Control rights. Click OK.
Private key permissions can be managed by right-clicking a cert in the certificate manager > All Tasks and then click "Manage Private Keys...". Windows User Access Control (UAC) prevents unprivileged users from gaining programmatic access to the private key, even if they are a member of the local administrators group.
509 certificate consists of two keys, namely a public key and a private key. This key pair, depending upon the application, allows you to sign documents using the private key so that the intended person can verify the signature using the public key related to it.
For this, open the “Certificate Signing Request (CSR)” menu, locate the CSR code for your certificate, scroll down to the bottom of the page and click the link under “This CSR uses the following key”: Just copy the Private key code from the following window and use it for further installation.
This answer is late but I wanted to post it for anybody else that comes searching in here:
I found an MSDN blog article that gave a solution using CryptoKeySecurity here, and here is an example of a solution in C#:
var rsa = certificate.PrivateKey as RSACryptoServiceProvider; if (rsa != null) { // Modifying the CryptoKeySecurity of a new CspParameters and then instantiating // a new RSACryptoServiceProvider seems to be the trick to persist the access rule. // cf. http://blogs.msdn.com/b/cagatay/archive/2009/02/08/removing-acls-from-csp-key-containers.aspx var cspParams = new CspParameters(rsa.CspKeyContainerInfo.ProviderType, rsa.CspKeyContainerInfo.ProviderName, rsa.CspKeyContainerInfo.KeyContainerName) { Flags = CspProviderFlags.UseExistingKey | CspProviderFlags.UseMachineKeyStore, CryptoKeySecurity = rsa.CspKeyContainerInfo.CryptoKeySecurity }; cspParams.CryptoKeySecurity.AddAccessRule(new CryptoKeyAccessRule(sid, CryptoKeyRights.GenericRead, AccessControlType.Allow)); using (var rsa2 = new RSACryptoServiceProvider(cspParams)) { // Only created to persist the rule change in the CryptoKeySecurity } }
I'm using a SecurityIdentifier to identify the account but an NTAccount would work just as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With