Windows Certificate installation via powershell


I have a powershell script to install a windows certificate and allow IIS_IUSRS access to the same. Here is the script.

#region Variables
    $CName = $args[0]
    $CPassword = $args[1]
    $CIssuedTo = $args[2]

#region Import certificate
    $CertificatePath = Join-Path -Path $PSScriptRoot -ChildPath $CName
    $pfxcert = new-object
    $pfxcert.Import($CertificatePath, $CPassword, [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]"PersistKeySet")

#region Add to Personal
    $store = Get-Item cert:\LocalMachine\My

#region Manage Private Keys
    $WinhttpPath = "$PSScriptRoot"

    if (Test-Path $WinhttpPath)
        &"$WinhttpPath\winhttpcertcfg.exe" -g -c LOCAL_MACHINE\My -s "$CIssuedTo" -a "IIS_IUSRS"
        throw "Winhttp component is not installed ($WinhttpPath)"

#region Add to TrustedPeople
    $store = Get-Item cert:\LocalMachine\TrustedPeople

This script works as expected and installs the certificate correctly. However, on trying to launch the site, I get an error:

Server Error in '/' Application.

The system cannot find the file specified.

  Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

 Exception Details: System.Security.Cryptography.CryptographicException: The system cannot find the file specified.

Source Error: 

 An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.  

Stack Trace: 

[CryptographicException: The system cannot find the file specified.
   System.Security.Cryptography.Utils.CreateProvHandle(CspParameters parameters, Boolean randomKeyContainer) +5528969
   System.Security.Cryptography.Utils.GetKeyPairHelper(CspAlgorithmType keyType, CspParameters parameters, Boolean randomKeyContainer, Int32 dwKeySize, SafeProvHandle& safeProvHandle, SafeKeyHandle& safeKeyHandle) +93
   System.Security.Cryptography.RSACryptoServiceProvider.GetKeyPair() +135
   System.Security.Cryptography.RSACryptoServiceProvider..ctor(Int32 dwKeySize, CspParameters parameters, Boolean useDefaultKeySize) +199
   System.Security.Cryptography.X509Certificates.X509Certificate2.get_PrivateKey() +229
   System.IdentityModel.X509Util.EnsureAndGetPrivateRSAKey(X509Certificate2 certificate) +133

[ArgumentException: ID1039: The certificate's private key could not be accessed. Ensure the access control list (ACL) on the certificate's private key grants access to the application pool user.
Thumbprint: '<ManuallyHidingThumbprintValueFromStackOverflowQuestion>']
   System.IdentityModel.X509Util.EnsureAndGetPrivateRSAKey(X509Certificate2 certificate) +705
   System.IdentityModel.RsaEncryptionCookieTransform..ctor(X509Certificate2 certificate) +105
   Thinktecture.IdentityServer.TokenService.X509CertificateSessionSecurityTokenHandler.CreateTransforms(X509Certificate2 protectionCertificate) +127
   Ed.IdentityServer.Web.STS.MvcApplication.<Application_Start>b__13_0(Object s, FederationConfigurationCreatedEventArgs e) +112
   System.IdentityModel.Services.FederatedAuthentication.OnFederationConfigurationCreated(FederationConfiguration federationConfiguration) +170
   System.IdentityModel.Services.FederatedAuthentication.CreateFederationConfiguration() +127
   System.IdentityModel.Services.FederatedAuthentication.get_FederationConfiguration() +103
   System.IdentityModel.Services.HttpModuleBase.Init(HttpApplication context) +99
   System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +581
   System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +168
   System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +414
   System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +369

[HttpException (0x80004005): ID1039: The certificate's private key could not be accessed. Ensure the access control list (ACL) on the certificate's private key grants access to the application pool user.
Thumbprint: '<ManuallyHidingThumbprintValueFromStackOverflowQuestion>']
   System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +532
   System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +111
   System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +714

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.7.2623.0 

Next, I login to the server. launch MMC->nagivate to certificate (and I see it there which means installation was ok?) -> More Actions -> all task -> manage private keys, and I see this image: enter image description here enter image description here This shows that IIS_IUSRS does have access.

I do nothing and try to launch website again and this time it works. I am trying to automate certificate installation and in this case it appears that I still have to manually "check?" if its installed correctly. This certificate is also present under Trusted People -> Certificates.

Why does it not work without me checking the private keys? What am I missing in the powershell script?

asked on Stack Overflow Sep 10, 2019 by skundu

1 Answer


Maybe you need change the "Owner" and in the image below and give IIS_IUSRS full permission by clicking "Change Permissions", click "Add" and search for IIS_IUSRS and give that user full permissions.

Change owner

Add User

answered on Stack Overflow Sep 10, 2019 by Manning

User contributions licensed under CC BY-SA 3.0