How to grant permission to private key from powershell

前端 未结 3 993
深忆病人
深忆病人 2021-01-19 20:13

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.

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-19 20:38

    Cmdlet code for getting private key filename.

    [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.

      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) 
    

提交回复
热议问题