PowerShell script to change permission of a certificate’s private key

/ November 1st, 2015/ Posted in PowerShell, Server / 1 Comment »

Problem:
I needed to change the permissions of a certificate’s private key in the windows local computer store on multiple servers. I use the certificate’s thumbprint to find the certificate and then apply the permissions to the user listed.

Solution:

$serviceAccount = 'NETWORK SERVICE'
$certThumbprint = 'x xx xx x xx xx xx dd dd ee ee ff ff gg hh 5e 20 3f 53 52'
$permissionType = 'Read'
    try
    {
        #Clear Existing Variables
        $cert = ''
        $keyFullPath = ''
        Write-Host "--------------------------"
        Write-Host "Server: $env:ComputerName" -ForegroundColor Cyan
        Write-Host "Finding Certificate..." -ForegroundColor Green
        #Get Certificate
        $cert = Get-ChildItem -Path cert:\LocalMachine\My | Where-Object {$_.Thumbprint -eq ($certThumbprint -replace '\s','')}
        If ($cert -ne $null -and $cert.PrivateKey.CspKeyContainerInfo.UniqueKeyContainerName -ne $null) 
        {
            # Get Location of the machine related keys
            $keyPath = $env:ProgramData + "\Microsoft\Crypto\RSA\MachineKeys\"; 
            $keyName = $cert.PrivateKey.CspKeyContainerInfo.UniqueKeyContainerName;
            $keyFullPath = $keyPath + $keyName;
            Write-Host "Found Certificate..." -ForegroundColor Green
            Write-Host "Granting access to $serviceAccount..." -ForegroundColor Green
            #Grant Full Control to account listed in $serviceAccount
            $acl = (Get-Item $keyFullPath).GetAccessControl('Access') #Get Current Access
            $buildAcl = New-Object  System.Security.AccessControl.FileSystemAccessRule($serviceAccount,$permissionType,"Allow") #Build Access Rule
            $acl.SetAccessRule($buildAcl) #Add Access Rule
            Set-Acl $keyFullPath $acl #Save Access Rules
            Write-Host "Access granted to $serviceAccount..." -ForegroundColor Green
            Write-Host "--------------------------"
        }
        Else {
            Write-Host "Unable to find Certificate that matches thumbprint $certThumbprint or the private key is missing..." -ForegroundColor Red
            Write-Host "--------------------------"
        }
    }
    catch
    {
        Write-Host "Unable to grant access to $serviceAccount..." -ForegroundColor Yellow
        Write-Host "--------------------------"
        throw $_;
    }

One Comment

  1. MO
    2017/07/27 at 04:38:15

    Thank you very much!

Leave a Reply

Name required

Please Submit Answer * Time limit is exhausted. Please reload CAPTCHA.