通过powershell安装Windows证书

通过powershell安装Windows证书,powershell,ssl-certificate,x509certificate,Powershell,Ssl Certificate,X509certificate,我有一个powershell脚本来安装windows证书并允许IIS\u IUSRS访问相同的证书。这是剧本 #region Variables $CName = $args[0] $CPassword = $args[1] $CIssuedTo = $args[2] #endregion #region Import certificate $CertificatePath = Join-Path -Path $PSScriptRoot -ChildPath

我有一个powershell脚本来安装windows证书并允许IIS\u 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 
“/”应用程序中出现服务器错误。 系统找不到指定的文件。 描述:执行当前web请求期间发生未处理的异常。请查看堆栈跟踪以了解有关错误的更多信息以及错误在代码中的起源。 异常详细信息:System.Security.Cryptography.Cryptography异常:系统找不到指定的文件。 源错误: 在执行当前web请求期间生成了未经处理的异常。有关异常的起源和位置的信息可以使用下面的异常堆栈跟踪来识别。 堆栈跟踪: [加密异常:系统找不到指定的文件。 ] System.Security.Cryptography.Utils.CreateProvHandle(CspParameters,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,Boolean useDefaultKeySize)+199 System.Security.Cryptography.X509Certificates.X509Certificate2.get_PrivateKey()+229 System.IdentityModel.X509Util.EnsureUnderingTPrivatersakey(X509Certificate2 certificate)+133 [ArgumentException:ID1039:无法访问证书的私钥。请确保证书私钥上的访问控制列表(ACL)授予应用程序池用户访问权限。 指纹:“”] System.IdentityModel.X509Util.EnsureEndegetPrivateSakey(X509Certificate2 certificate)+705 系统标识模型RSA加密CookieTransform..ctor(X509Certificate2 certificate)+105 Thinktecture.IdentityServer.TokenService.X509CertificateSessionSecurityTokenHandler.CreateTransforms(X509Certificate2 protectionCertificate)+127 Ed.IdentityServer.Web.STS.mvcapapplication。 这表明IIS_IUSR确实具有访问权限

我什么也不做,并试图再次启动该网站,这一次它的工作。我正在尝试自动安装证书,在这种情况下,如果证书安装正确,我似乎仍然需要手动“检查”。此证书也存在于Trusted People->Certificates下

为什么我不检查私钥它就不能工作?我在powershell脚本中遗漏了什么

也许您需要更改“所有者”并在下图中单击“更改权限”授予IIS\u IUSRS完全权限,单击“添加”并搜索IIS\u IUSRS并授予该用户完全权限


感谢您的回复。查看“管理私钥”选项后,我无需更改任何内容。到目前为止,似乎只有在我查看证书的管理私钥后才应用权限,这对我来说似乎没有意义。@skundu可能会添加一个答案,概述您的解决方案,以便其他人可以找到并使用它?我相信,您必须在
$pfxcert.Import
方法调用中使用
MachineKeySet
标志。另外,请确保
$cisuedto
变量是否正确并且与证书中的值匹配。感谢您的建议,但是MachineKeySet无法工作。