简体   繁体   English

通过Powershell安装Windows证书

[英]Windows Certificate installation via powershell

I have a powershell script to install a windows certificate and allow IIS_IUSRS access to the same. 我有一个Powershell脚本来安装Windows证书,并允许IIS_IUSRS访问该证书。 Here is the script. 这是脚本。

#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

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: 启动MMC-> nagivate到证书(我在那里看到这意味着安装可以吗?)->更多操作->所有任务->管理私钥,我看到此图像: 在此处输入图片说明 在此处输入图片说明 This shows that IIS_IUSRS does have access. 这表明IIS_IUSRS确实具有访问权限。

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? 我在Powershell脚本中缺少什么?

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. 也许您需要更改“所有者”并在下面的图像中,通过单击“更改权限”为IIS_IUSRS授予完全权限,单击“添加”并搜索IIS_IUSRS并为该用户授予完全权限。

变更拥有者

添加用户

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM