首页 > 解决方案 > 如何从PowerShell中的证书私钥中删除用户

问题描述

您好我正在尝试创建一个脚本,我可以在其中从证书中的私钥中删除 userAccess 但是我不断收到此错误。我以管理员身份运行它

New-Object : Exception calling ".ctor" with "1" argument(s): "Bad Key.
 $rsa2 = New-Object System.Security.Cryptography.RSACryptoServiceP ...

下面的脚本

Function GrantCertAccess{
  Write-OutPut "Granting certificate permision to  TestUser "     
 $accountName="TestUser"; 
 
 
if(net user $accountName)
{   
    
            
           $certificate=Get-ChildItem  -Path Cert:\LocalMachine\MY | Where-Object {$_.Subject -Match "WebCert"} 
            $store = New-Object System.Security.Cryptography.X509Certificates.X509Store("My","LocalMachine")
            $store.Open("ReadWrite")
            $rwCert = $store.Certificates | where {$_.Thumbprint -eq $certificate.Thumbprint}
            $csp = New-Object System.Security.Cryptography.CspParameters($rwCert.PrivateKey.CspKeyContainerInfo.ProviderType, $rwCert.PrivateKey.CspKeyContainerInfo.ProviderName, $rwCert.PrivateKey.CspKeyContainerInfo.KeyContainerName)
            $csp.Flags = "UseExistingKey","UseMachineKeyStore"
            $csp.CryptoKeySecurity = $rwCert.PrivateKey.CspKeyContainerInfo.CryptoKeySecurity
            $csp.KeyNumber = $rwCert.PrivateKey.CspKeyContainerInfo.KeyNumbe
            $user = New-Object System.Security.Principal.NTAccount($accountName)
            Write-Output $user
            $str_Identity = ( [System.Environment]::MachineName+"\"+$user.Value)
   
            $x = $csp.CryptoKeySecurity.Access
             Write-Output "passed"
       
            foreach($ruleitem in $x)
            {
            
               if($ruleitem.IdentityReference.Value -eq $str_Identity)
               {
                 $csp.CryptoKeySecurity.RemoveAccessRule($ruleitem)

               }
             
            }

       
            $rsa2 = New-Object System.Security.Cryptography.RSACryptoServiceProvider($csp)
            $store.close()
                Write-OutPut "TestUser is removed from the private key of cert successfully "
          
                    
            
}}

将不胜感激的帮助谢谢

标签: windowspowershellcertificatepowershell-2.0powershell-3.0

解决方案


推荐阅读