2

I'm trying to import a certificate with private key into the Windows Certificate Store. I can successfully import the certificate using the below

X509Certificate2 certificate = new(certByteArray, certPassword, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet);
X509Store store = new(StoreName.TrustedPeople, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadWrite);
store.Add(certificate);

But the problem I've got is, how to give a user access to the private key programmatically.
I've found these links helpful:
https://www.pkisolutions.com/accessing-and-using-certificate-private-keys-in-net-framework-net-core/
CngKey Assign permission to machine key

Set Certificate PrivateKey Permissions in .NET 5

I can grant access via the UI with certlm.msc > Drag certificate to Personal store > Right click certificate > All Tasks > Manage private keys > Add the user and permission
But I need to do this programmatically

There are changes from .NET Full Framework which is where the examples come from. I've spent more than a day on it, tried multiple certificates, certificate is definitely marked as exportable and running VS as administrator. I'm happy with a Windows only solution

This is about as close as I've got

const string NCRYPT_SECURITY_DESCR_PROPERTY = "Security Descr";
const CngPropertyOptions DACL_SECURITY_INFORMATION = (CngPropertyOptions)4;

X509Store trustedPeopleStore = new(StoreName.TrustedPeople, StoreLocation.LocalMachine);
trustedPeopleStore.Open(OpenFlags.ReadWrite);

var certificates = trustedPeopleStore.Certificates.Find(X509FindType.FindByThumbprint, "xxxxxxxxxxxxxxxxxxxxxx", false);

RSA rsa = certificates[0].GetRSAPrivateKey();
RSACng rsaCng = rsa as RSACng;

CngProperty prop = rsaCng.Key.GetProperty(NCRYPT_SECURITY_DESCR_PROPERTY, DACL_SECURITY_INFORMATION);

I can see the rsaCng.Key present in debug, but it fails on the next line (it definitely is exportable) getting the property with Internal.Cryptography.CryptoThrowHelper.WindowsCryptographicException: 'Key not valid for use in specified state.' I've also read comments that you shouldn't try setting the acl directly on the file, but not sure if that is correct or not

SpeedBird527
  • 149
  • 2
  • 4
  • 18
  • My guess would be that the user running you WebApp doesn't have the required permission to access the cert store. Did you try saving all the Private Keys in a folder in your App_Data and then give access to them based on user logins? – Charles Nov 29 '21 at 05:06

1 Answers1

0

See this code project post for some example code that grants access programmatically (specifically look at the "AddAccessToCertificate" method).

Check this for more info: Programmatically adding certificate to personal store

Danut Radoaica
  • 1,860
  • 13
  • 17