且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从powershell授予私钥权限

更新时间:2022-11-25 09:55:51

用于获取私钥文件名的 Cmdlet 代码.

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");
    }
}

使用 cmdlet.CngCrypt.dll - 带有 cmdlet 代码的 dll.

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)