Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Function Get-PrivateKeyContainerPath
- {
- [CmdletBinding(PositionalBinding=$false)]
- Param(
- [Parameter(Mandatory=$True)][string][ValidateNotNullOrEmpty()] $Name,
- [Parameter(Mandatory=$True)][boolean] $IsCNG
- )
- If ($IsCNG)
- {
- $searchDirectories = @("Microsoft\Crypto\Keys","Microsoft\Crypto\SystemKeys")
- }
- else
- {
- $searchDirectories = @(
- "Microsoft\Crypto\RSA\MachineKeys",
- "Microsoft\Crypto\RSA\S-1-5-18",
- "Microsoft\Crypto\RSA\S-1-5-19",
- "Crypto\DSS\S-1-5-20"
- )
- }
- foreach ($searchDirectory in $searchDirectories)
- {
- $machineKeyDirectory = Join-Path -Path $([Environment]::GetFolderPath("CommonApplicationData")) -ChildPath $searchDirectory
- $privateKeyFile = Get-ChildItem -Path $machineKeyDirectory -Filter $Name -Recurse
- if ($null -ne $privateKeyFile)
- {
- return $privateKeyFile.FullName
- break
- }
- }
- Throw "Cannot find private key file path for key container ""$Name"""
- }
- ...
- $dllPath = "$curDir\Security.Cryptography.dll"
- if (Test-Path $dllPath)
- {
- # Load the Assembly
- [System.Reflection.Assembly]::LoadFile($dllPath)
- $Certificate = Get-ChildItem "Cert:\LocalMachine\My\$SHA1Thumbprint"
- if ([Security.Cryptography.X509Certificates.X509CertificateExtensionMethods]::HasCngKey($Certificate))
- {
- Write-Verbose "Private Key is CNG"
- $privateKey = [Security.Cryptography.X509Certificates.X509Certificate2ExtensionMethods]::GetCngPrivateKey($Certificate)
- $keyContainerName = $privateKey.UniqueName
- $privateKeyPath = Get-PrivateKeyContainerPath -Name $keyContainerName -IsCNG $true
- }
- elseif ($null -ne $Certificate.PrivateKey)
- {
- Write-Verbose "Private Key CSP is Legacy"
- $privateKey = $Certificate.PrivateKey
- $keyContainerName = $privateKey.CspKeyContainerInfo.UniqueKeyContainerName
- $privateKeyPath = Get-PrivateKeyContainerPath -Name $keyContainerName -IsCNG $false
- }
- else
- {
- throw "Certificate `"$($Certificate.GetNameInfo("SimpleName",$false))`" does not have a private key, or that key is inaccessible, therefore permission not granted"
- }
- # Grant the "Network Service" read access to the private key
- $Acl = Get-Acl -Path $privateKeyPath
- $permission = "NT AUTHORITY\NETWORK SERVICE", "Read", "Allow"
- $rule = New-Object System.Security.AccessControl.FileSystemAccessRule $permission
- $Acl.AddAccessRule($rule)
- Set-Acl $privateKeyPath $Acl -Verbose
- }
Add Comment
Please, Sign In to add comment