Question:
I’m trying to find a way to grant permissions for private key from powershell script. Certificate is stored in CNG. All ideas are welcome.
Answer:
Cmdlet code for getting private key filename.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
[Cmdlet("Get", "PrivateKeyName")] public class GetKeyNameCmdlet : Cmdlet { [Parameter(Position = 0, Mandatory = false)] public X509Certificate2 Cert; protected override void ProcessRecord() { WriteObject(GetUniqueKeyName(Cert)); } private static string GetUniqueKeyName(X509Certificate2 cert) { if (cert == null) throw new ArgumentNullException("cert"); var cngPrivateKey = cert.GetCngPrivateKey(); if (cngPrivateKey != null) return cngPrivateKey.UniqueName; var rsaPrivateKey = cert.PrivateKey as RSACryptoServiceProvider; if (rsaPrivateKey != null) return rsaPrivateKey.CspKeyContainerInfo.UniqueKeyContainerName; throw new Exception("cert"); } } |
using cmdlet. CngCrypt.dll – dll with cmdlet code.
1 2 3 4 5 |
Import-Module .\CngCrypt.dll $local:certificateRootPath = join-path $env:ALLUSERSPROFILE '\Microsoft\Crypto\RSA\MachineKeys\' $WorkingCert = Get-ChildItem CERT:\LocalMachine\My |where {$_.Subject -match 'Test'}| sort Get-PrivateKeyName ($WorkingCert) |