How to set read permission on the private key file of X.509 certificate from .NET

前端 未结 6 1391
遥遥无期
遥遥无期 2020-11-28 07:12

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

X509Store store = new X509Store( StoreName.My, StoreLocation.LocalMachine );
store.Open( OpenFlags.ReadWrite         


        
6条回答
  •  孤独总比滥情好
    2020-11-28 07:48

    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.

提交回复
热议问题