Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- param(
- [string]$certStore = "LocalMachineTrustedPeople",
- [string]$filename = "sp.pfx",
- [string]$password = "password",
- [string]$username = "$Env:COMPUTERNAMEWebSiteUser"
- )
- function getKeyFilePath($cert) {
- return "$ENV:ProgramDataMicrosoftCryptoRSAMachineKeys" + $cert.PrivateKey.CspKeyContainerInfo.UniqueKeyContainerName
- }
- $certFromFile = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($filename, $password)
- $certFromStore = Get-ChildItem "Cert:$certStore" | Where-Object {$_.Thumbprint -eq $certFromFile.Thumbprint}
- $certExistsInStore = $certFromStore.Count -gt 0
- $keyExists = $certExistsInStore -and ($certFromStore.PrivateKey -ne $null) -and (Test-Path(getKeyFilePath($certFromStore)))
- if ((!$certExistsInStore) -or (!$keyExists)) {
- $keyFlags = [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::MachineKeySet
- $keyFlags = $keyFlags -bor [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::PersistKeySet
- $certFromFile.Import($filename, $password, $keyFlags)
- $store = Get-Item "Cert:$certStore"
- $store.Open("ReadWrite")
- if ($certExistsInStore) {
- #Cert is in the store, but we have no persisted private key
- #Remove it so we can add the one we just imported with the key file
- $store.Remove($certFromStore)
- }
- $store.Add($certFromFile)
- $store.Close()
- $certFromStore = $certFromFile
- "Installed x509 certificate"
- }
- $pkFile = Get-Item(getKeyFilePath($certFromStore))
- $pkAcl = $pkFile.GetAccessControl("Access")
- $readPermission = $username,"Read","Allow"
- $readAccessRule = new-object System.Security.AccessControl.FileSystemAccessRule $readPermission
- $pkAcl.AddAccessRule($readAccessRule)
- Set-Acl $pkFile.FullName $pkAcl
- "Granted read permission on private key to web user"
Add Comment
Please, Sign In to add comment