Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save milesgratz/38804dfc336df64191f958004953e9b6 to your computer and use it in GitHub Desktop.
Save milesgratz/38804dfc336df64191f958004953e9b6 to your computer and use it in GitHub Desktop.
PowerShell example of updating machine certificate private key permissions (CAPI vs CNG)
# Get cert on local computer by thumbprint
$thumbprint = '89D3FC64B6405E161EDC7A4CF14E111F5F6895AA'
$Cert = Get-ChildItem Cert:\LocalMachine\My | Where-Object { $_.Thumbprint -eq $thumbprint }
###################################################
# Manage private key of CAPI cert
###################################################
# Find private key
$privKey = $Cert.PrivateKey.CspKeyContainerInfo.UniqueKeyContainerName
$keyPath = "$($env:ProgramData)\Microsoft\Crypto\RSA\MachineKeys\"
$privKeyPath = (Get-Item "$keyPath\$privKey")
# Update ACL to allow "READ" permissions from "NT AUTHORITY\NETWORK SERVICE"
$Acl = Get-Acl $privKeyPath
$Ar = New-Object System.Security.AccessControl.FileSystemAccessRule("NETWORK SERVICE", "Read", "Allow")
$Acl.SetAccessRule($Ar)
Set-Acl $privKeyPath.FullName $Acl
###################################################
# Manage private key of CNG cert
###################################################
# Find CNG (rsa) private key
$privKey = ([System.Security.Cryptography.X509Certificates.RSACertificateExtensions]::GetRSAPrivateKey($Cert)).key.UniqueName
$keyPath = "$($env:ProgramData)\Microsoft\Crypto\Keys\"
$privKeyPath = (Get-Item "$keyPath\$privKey")
# Update ACL to allow "READ" permissions from "NT AUTHORITY\NETWORK SERVICE"
$Acl = Get-Acl $privKeyPath
$Ar = New-Object System.Security.AccessControl.FileSystemAccessRule("NETWORK SERVICE", "Read", "Allow")
$Acl.SetAccessRule($Ar)
Set-Acl $privKeyPath.FullName $Acl
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment