通过Powershell安装Windows证书

时间:2019-09-10 17:40:54

标签: powershell ssl-certificate x509certificate

我有一个Powershell脚本来安装Windows证书,并允许IIS_IUSRS访问该证书。这是脚本。

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

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

#region Add to Personal
    $store = Get-Item cert:\LocalMachine\My
    $store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]"ReadWrite")
    $store.add($pfxcert)
    $store.Close()
#endregion

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

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

#region Add to TrustedPeople
    $store = Get-Item cert:\LocalMachine\TrustedPeople
    $store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]"ReadWrite")
    $store.add($pfxcert)
    $store.Close()
#endregion

此脚本可以按预期工作并正确安装证书。但是,在尝试启动该网站时,出现错误:

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 

接下来,我登录到服务器。启动MMC-> nagivate到证书(我在那里看到这意味着安装可以吗?)->更多操作->所有任务->管理私钥,我看到此图像: enter image description here enter image description here 这表明IIS_IUSRS确实具有访问权限。

我什么也没做,尝试再次启动网站,这次它可以工作了。我正在尝试自动执行证书安装,在这种情况下,我仍然需要手动“检查”?如果安装正确。该证书也位于“受信任的人->证书”下。

为什么没有我检查私钥怎么办?我在Powershell脚本中缺少什么?

1 个答案:

答案 0 :(得分:0)

也许您需要更改“所有者”,然后在下图中,通过单击“更改权限”为IIS_IUSRS授予完全权限,单击“添加”并搜索IIS_IUSRS并为该用户授予完全权限。

Change owner

Add User