Guest User

Untitled

a guest
Jun 2nd, 2016
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.79 KB | None | 0 0
  1. param(
  2. [string]$certStore = "LocalMachineTrustedPeople",
  3. [string]$filename = "sp.pfx",
  4. [string]$password = "password",
  5. [string]$username = "$Env:COMPUTERNAMEWebSiteUser"
  6. )
  7.  
  8. function getKeyFilePath($cert) {
  9. return "$ENV:ProgramDataMicrosoftCryptoRSAMachineKeys" + $cert.PrivateKey.CspKeyContainerInfo.UniqueKeyContainerName
  10. }
  11.  
  12. $certFromFile = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($filename, $password)
  13. $certFromStore = Get-ChildItem "Cert:$certStore" | Where-Object {$_.Thumbprint -eq $certFromFile.Thumbprint}
  14. $certExistsInStore = $certFromStore.Count -gt 0
  15. $keyExists = $certExistsInStore -and ($certFromStore.PrivateKey -ne $null) -and (Test-Path(getKeyFilePath($certFromStore)))
  16.  
  17. if ((!$certExistsInStore) -or (!$keyExists)) {
  18.  
  19. $keyFlags = [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::MachineKeySet
  20. $keyFlags = $keyFlags -bor [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::PersistKeySet
  21. $certFromFile.Import($filename, $password, $keyFlags)
  22.  
  23. $store = Get-Item "Cert:$certStore"
  24. $store.Open("ReadWrite")
  25.  
  26. if ($certExistsInStore) {
  27. #Cert is in the store, but we have no persisted private key
  28. #Remove it so we can add the one we just imported with the key file
  29. $store.Remove($certFromStore)
  30. }
  31.  
  32. $store.Add($certFromFile)
  33. $store.Close()
  34.  
  35. $certFromStore = $certFromFile
  36. "Installed x509 certificate"
  37. }
  38.  
  39. $pkFile = Get-Item(getKeyFilePath($certFromStore))
  40. $pkAcl = $pkFile.GetAccessControl("Access")
  41. $readPermission = $username,"Read","Allow"
  42. $readAccessRule = new-object System.Security.AccessControl.FileSystemAccessRule $readPermission
  43. $pkAcl.AddAccessRule($readAccessRule)
  44. Set-Acl $pkFile.FullName $pkAcl
  45. "Granted read permission on private key to web user"
Add Comment
Please, Sign In to add comment