Home > database >  (NET6 ) Grant user read permission on certificate's private key
(NET6 ) Grant user read permission on certificate's private key

Time:07-20

Windows stores certificate's private keys as files, and you can use mmc.exe to give users read permissions on these keys. I need a way to do that programatically in NET6.

Microsoft have marked the PrivateKey property on the X509Certificate class as obsolete (since .NET 4.6) and the correct way is to use the extension methods provided.

However, the returned RSA key class does not contain a UniqueName property which I can then use to determine the filename of the private key, and thus grant a user read permission on it.

This question Grant user permission to the private key shows how it can be achieved using the obsolete property name.

Does anyone know how this can be achieved without using the PrivateKey property?

CodePudding user response:

I had some luck with this:

// input: "X509Certificate2 cert"
RSACng rsa = cert.GetRSAPrivateKey() as RSACng;
string rsaKeyName = rsa.Key.UniqueName;
if (rsaKeyName == null)
{
    RSACryptoServiceProvider rsaCSP = cert.GetRSAPrivateKey() as RSACryptoServiceProvider;
    rsaKeyName = rsaCSP.CspKeyContainerInfo.KeyContainerName;
}
  • Related