I want to create or obtain a certificate, create a pfx-file, load it and have IdentityServer use it. However, IdentityServer is not able to use my pfx.
我想创建或获取证书,创建一个pfx文件,加载它并让IdentityServer使用它。但是,身份服务器不能使用我的PFX。
How to successfully create a pfx and have IdentityServer use it?
如何成功创建一个PFX并让身份服务器使用它?
I have an IdentityServer4 web solution running on localhost with ASP.Net Core. I am preparing the solution for production running on Azure, and is adding a certificate to the IdentityServer pipeline instead of the developer signing certificate.
我有一个运行在带有ASP.NET核心的本地主机上的标识服务器4 Web解决方案。我正在为在Azure上运行的产品准备解决方案,并将证书添加到标识服务器管道中,而不是开发人员签名证书。
Typically this means to swap code like
通常这意味着交换代码,如下所示
services.AddIdentityServer()
.AddDeveloperSigningCredential()
with
使用
services.AddIdentityServer()
.AddSigningCredential(cert)
where "cert" is an object instance of X509Certificate2 which has loaded a PFX-file containing the certificate (with public and private keys).
其中“cert”是已加载了包含证书(带有公钥和私钥)的pfx文件的X509cerficate2的对象实例。
The certificate I am using is self signed and is created by following the steps on Ben Cull's Blog https://benjii.me/2017/06/creating-self-signed-certificate-identity-server-azure/
我正在使用的证书是自签名的,并且是按照本·卡尔的博客https://benjii.me/2017/06/creating-self-signed-certificate-identity-server-azure/上的步骤创建的
The certicate and private key is exported to a PFX-file in order for both public and private key to be contained in the file.
证书和私钥被导出到pfx文件,以便将公钥和私钥都包含在该文件中。
The loading of the PFX-file succeeds. The code for loading is
加载pfx文件成功。加载代码为
cert = new X509Certificate2(Path.Combine(Environment.ContentRootPath, "MyPfxFile.pfx"), "password-used-when-exporting-pfx");
The Pfx-file is located within the web project and is found and read into the X509Certificate object.
Pfx文件位于Web项目中,可以找到该文件并将其读入X509证书对象。
When inspecting the X509Certificate2 in Visual Studio the property HasPrivateKey return true, but the PrivateKey property resolves to an exception in the watcher.
在Visual Studio中检查X509证书2时,属性HasPrivateKey返回True,但PrivateKey属性在监视器中解析为异常。
'cert.PrivateKey' threw an exception of type 'Internal.Cryptography.CryptoThrowHelper.WindowsCryptographicException'
All other properties look sound and good in the watcher.
所有其他属性在观察者中看起来都很好。
Also, when I execute the GetRSAPrivateKey in the Immediate Window method on the certificate object instance, it returns an exception.
此外,当我在证书对象实例的即时窗口方法中执行GetRSAPrivateKey时,它返回异常。
cert.GetRSAPrivateKey()
'cert.GetRSAPrivateKey()' threw an exception of type 'Internal.Cryptography.CryptoThrowHelper.WindowsCryptographicException'
Data: {System.Collections.ListDictionaryInternal}
HResult: -2146893798
HelpLink: null
InnerException: null
Message: "Keyset as registered is invalid"
Source: "System.Security.Cryptography.Csp"
StackTrace: " at Internal.NativeCrypto.CapiHelper.CreateProvHandle(CspParameters parameters, Boolean randomKeyContainer)\r\n at System.Security.Cryptography.RSACryptoServiceProvider.get_SafeProvHandle()\r\n at System.Security.Cryptography.RSACryptoServiceProvider.get_SafeKeyHandle()\r\n at System.Security.Cryptography.RSACryptoServiceProvider..ctor(Int32 keySize, CspParameters parameters, Boolean useDefaultKeySize)\r\n at System.Security.Cryptography.RSACryptoServiceProvider..ctor(CspParameters parameters)\r\n at Internal.Cryptography.Pal.CertificatePal.<>c.<GetRSAPrivateKey>b__61_0(CspParameters csp)\r\n at Internal.Cryptography.Pal.CertificatePal.GetPrivateKey[T](Func`2 createCsp, Func`2 createCng)\r\n at Internal.Cryptography.Pal.CertificatePal.GetRSAPrivateKey()\r\n at Internal.Cryptography.Pal.CertificateExtensionsCommon.GetPrivateKey[T](X509Certificate2 certificate, Predicate`1 matchesConstraints)\r\n at System.Security.Cryptography.X509Certificates.RSACertificateExtensions.GetRSA
PrivateKey(X509Certificate2 certificate)"
TargetSite: {System.Security.Cryptography.SafeProvHandle CreateProvHandle(System.Security.Cryptography.CspParameters, Boolean)}
I have tried loading the pfx-file with different settings for X509KeyStorageFlags, but the behaviour and exceptions are the same.
我尝试用不同的X509Keywords Flags设置加载pfx文件,但行为和异常是相同的。
I have also tried to install the PFX into the Windows machine's certificate manager, and I am successfully loading it from there, but the same exceptions are thrown.
我还尝试将PFX安装到Windows计算机的证书管理器中,并成功地从那里加载了它,但抛出了相同的异常。
At last, when requesting an access token from IdentityServer, the same exception is thrown. I have pasted the exception trace below.
最后,当从标识服务器请求访问令牌时,也会抛出同样的异常。我已经在下面粘贴了异常跟踪。
IdentityServer4.Hosting.IdentityServerMiddleware:Critical: Unhandled exception: Internal.Cryptography.CryptoThrowHelper+WindowsCryptographicException: Keyset as registered is invalid
at Internal.NativeCrypto.CapiHelper.CreateProvHandle(CspParameters parameters, Boolean randomKeyContainer)
at System.Security.Cryptography.RSACryptoServiceProvider.get_SafeProvHandle()
at System.Security.Cryptography.RSACryptoServiceProvider.get_SafeKeyHandle()
at System.Security.Cryptography.RSACryptoServiceProvider..ctor(Int32 keySize, CspParameters parameters, Boolean useDefaultKeySize)
at System.Security.Cryptography.RSACryptoServiceProvider..ctor(CspParameters parameters)
at Internal.Cryptography.Pal.CertificatePal.<>c.<GetRSAPrivateKey>b__61_0(CspParameters csp)
at Internal.Cryptography.Pal.CertificatePal.GetPrivateKey[T](Func`2 createCsp, Func`2 createCng)
at Internal.Cryptography.Pal.CertificatePal.GetRSAPrivateKey()
at Internal.Cryptography.Pal.CertificateExtensionsCommon.GetPrivateKey[T](X509Certificate2 certificate, Predicate`1 matchesConstraints)
at System.Security.Cryptography.X509Certificates.RSACertificateExtensions.GetRSAPrivateKey(X509Certificate2 certificate)
at Microsoft.IdentityModel.Tokens.X509SecurityKey.get_PrivateKey()
at Microsoft.IdentityModel.Tokens.X509SecurityKey.get_HasPrivateKey()
at Microsoft.IdentityModel.Tokens.AsymmetricSignatureProvider.HasPrivateKey(SecurityKey key)
at Microsoft.IdentityModel.Tokens.AsymmetricSignatureProvider..ctor(SecurityKey key, String algorithm, Boolean willCreateSignatures)
at Microsoft.IdentityModel.Tokens.CryptoProviderFactory.CreateSignatureProvider(SecurityKey key, String algorithm, Boolean willCreateSignatures)
at Microsoft.IdentityModel.Tokens.CryptoProviderFactory.CreateForSigning(SecurityKey key, String algorithm)
at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.CreateEncodedSignature(String input, SigningCredentials signingCredentials)
at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.WriteToken(SecurityToken token)
at IdentityServer4.Services.DefaultTokenCreationService.CreateJwtAsync(JwtSecurityToken jwt) in C:\local\identity\server4\IdentityServer4\src\IdentityServer4\Services\DefaultTokenCreationService.cs:line 209
at IdentityServer4.Services.DefaultTokenCreationService.<CreateTokenAsync>d__4.MoveNext() in C:\local\identity\server4\IdentityServer4\src\IdentityServer4\Services\DefaultTokenCreationService.cs:line 67
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at IdentityServer4.Services.DefaultTokenService.<CreateSecurityTokenAsync>d__9.MoveNext() in C:\local\identity\server4\IdentityServer4\src\IdentityServer4\Services\DefaultTokenService.cs:line 210
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at IdentityServer4.ResponseHandling.TokenResponseGenerator.<CreateAccessTokenAsync>d__14.MoveNext() in C:\local\identity\server4\IdentityServer4\src\IdentityServer4\ResponseHandling\TokenResponseGenerator.cs:line 313
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at IdentityServer4.ResponseHandling.TokenResponseGenerator.<ProcessAuthorizationCodeRequestAsync>d__10.MoveNext() in C:\local\identity\server4\IdentityServer4\src\IdentityServer4\ResponseHandling\TokenResponseGenerator.cs:line 133
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at IdentityServer4.ResponseHandling.TokenResponseGenerator.<ProcessAsync>d__7.MoveNext() in C:\local\identity\server4\IdentityServer4\src\IdentityServer4\ResponseHandling\TokenResponseGenerator.cs:line 88
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at IdentityServer4.Endpoints.TokenEndpoint.<ProcessTokenRequestAsync>d__7.MoveNext() in C:\local\identity\server4\IdentityServer4\src\IdentityServer4\Endpoints\TokenEndpoint.cs:line 98
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at IdentityServer4.Endpoints.TokenEndpoint.<ProcessAsync>d__6.MoveNext() in C:\local\identity\server4\IdentityServer4\src\IdentityServer4\Endpoints\TokenEndpoint.cs:line 70
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at IdentityServer4.Hosting.IdentityServerMiddleware.<Invoke>d__3.MoveNext() in C:\local\identity\server4\IdentityServer4\src\IdentityServer4\Hosting\IdentityServerMiddleware.cs:line 54
Application Insights Telemetry (unconfigured): {"name":"Microsoft.ApplicationInsights.Dev.Message","time":"2018-10-17T09:19:34.1583055Z","tags":{"ai.application.ver":"1.0.0.0","ai.cloud.roleInstance":"HEBE","ai.operation.id":"d7c51fcd-421c862dd08fe813","ai.operation.parentId":"|d7c51fcd-421c862dd08fe813.","ai.operation.name":"POST /connect/token","ai.location.ip":"127.0.0.1","ai.internal.sdkVersion":"aspnet5c:2.1.1","ai.internal.nodeName":"HEBE"},"data":{"baseType":"MessageData","baseData":{"ver":2,"message":"Unhandled exception: Internal.Cryptography.CryptoThrowHelper+WindowsCryptographicException: Keyset as registered is invalid\r\n at Internal.NativeCrypto.CapiHelper.CreateProvHandle(CspParameters parameters, Boolean randomKeyContainer)\r\n at System.Security.Cryptography.RSACryptoServiceProvider.get_SafeProvHandle()\r\n at System.Security.Cryptography.RSACryptoServiceProvider.get_SafeKeyHandle()\r\n at System.Security.Cryptography.RSACryptoServiceProvider..ctor(Int32 keySize, CspParameters parameters, Boolean useDefaultKeySize)\r\n at System.Security.Cryptography.RSACryptoServiceProvider..ctor(CspParameters parameters)\r\n at Internal.Cryptography.Pal.CertificatePal.<>c.<GetRSAPrivateKey>b__61_0(CspParameters csp)\r\n at Internal.Cryptography.Pal.CertificatePal.GetPrivateKey[T](Func`2 createCsp, Func`2 createCng)\r\n at Internal.Cryptography.Pal.CertificatePal.GetRSAPrivateKey()\r\n at Internal.Cryptography.Pal.CertificateExtensionsCommon.GetPrivateKey[T](X509Certificate2 certificate, Predicate`1 matchesConstraints)\r\n at System.Security.Cryptography.X509Certificates.RSACertificateExtensions.GetRSAPrivateKey(X509Certificate2 certificate)\r\n at Microsoft.IdentityModel.Tokens.X509SecurityKey.get_PrivateKey()\r\n at Microsoft.IdentityModel.Tokens.X509SecurityKey.get_HasPrivateKey()\r\n at Microsoft.IdentityModel.Tokens.AsymmetricSignatureProvider.HasPrivateKey(SecurityKey key)\r\n at Microsoft.IdentityModel.Tokens.AsymmetricSignatureProvider..ctor(SecurityKey key, String algorithm, Boolean willCreateSignatures)\r\n at Microsoft.IdentityModel.Tokens.CryptoProviderFactory.CreateSignatureProvider(SecurityKey key, String algorithm, Boolean willCreateSignatures)\r\n at Microsoft.IdentityModel.Tokens.CryptoProviderFactory.CreateForSigning(SecurityKey key, String algorithm)\r\n at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.CreateEncodedSignature(String input, SigningCredentials signingCredentials)\r\n at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.WriteToken(SecurityToken token)\r\n at IdentityServer4.Services.DefaultTokenCreationService.CreateJwtAsync(JwtSecurityToken jwt) in C:\\local\\identity\\server4\\IdentityServer4\\src\\IdentityServer4\\Services\\DefaultTokenCreationService.cs:line 209\r\n at IdentityServer4.Services.DefaultTokenCreationService.<CreateTokenAsync>d__4.MoveNext() in C:\\local\\identity\\server4\\IdentityServer4\\src\\IdentityServer4\\Services\\DefaultTokenCreationService.cs:line 67\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at IdentityServer4.Services.DefaultTokenService.<CreateSecurityTokenAsync>d__9.MoveNext() in C:\\local\\identity\\server4\\IdentityServer4\\src\\IdentityServer4\\Services\\DefaultTokenService.cs:line 210\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at IdentityServer4.ResponseHandling.TokenResponseGenerator.<CreateAccessTokenAsync>d__14.MoveNext() in C:\\local\\identity\\server4\\IdentityServer4\\src\\IdentityServer4\\ResponseHandling\\TokenResponseGenerator.cs:line 313\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at IdentityServer4.ResponseHandling.TokenResponseGenerator.<ProcessAuthorizationCodeRequestAsync>d__10.MoveNext() in C:\\local\\identity\\server4\\IdentityServer4\\src\\IdentityServer4\\ResponseHandling\\TokenResponseGenerator.cs:line 133\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at IdentityServer4.ResponseHandling.TokenResponseGenerator.<ProcessAsync>d__7.MoveNext() in C:\\local\\identity\\server4\\IdentityServer4\\src\\IdentityServer4\\ResponseHandling\\TokenResponseGenerator.cs:line 88\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at IdentityServer4.Endpoints.TokenEndpoint.<ProcessTokenRequestAsync>d__7.MoveNext() in C:\\local\\identity\\server4\\IdentityServer4\\src\\IdentityServer4\\Endpoints\\TokenEndpoint.cs:line 98\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at IdentityServer4.Endpoints.TokenEndpoint.<ProcessAsync>d__6.MoveNext() in C:\\local\\identity\\server4\\IdentityServer4\\src\\IdentityServer4\\Endpoints\\TokenEndpoint.cs:line 70\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at IdentityServer4.Hosting.IdentityServerMiddleware.<Invoke>d__3.MoveNext() in C:\\local\\identity\\server4\\IdentityServer4\\src\\IdentityServer4\\Hosting\\IdentityServerMiddleware.cs:line 54","severityLevel":"Critical","properties":{"DeveloperMode":"true","AspNetCoreEnvironment":"Development","{OriginalFormat}":"Unhandled exception: {exception}","exception":"Internal.Cryptography.CryptoThrowHelper+WindowsCryptographicException: Keyset as registered is invalid\r\n at Internal.NativeCrypto.CapiHelper.CreateProvHandle(CspParameters parameters, Boolean randomKeyContainer)\r\n at System.Security.Cryptography.RSACryptoServiceProvider.get_SafeProvHandle()\r\n at System.Security.Cryptography.RSACryptoServiceProvider.get_SafeKeyHandle()\r\n at System.Security.Cryptography.RSACryptoServiceProvider..ctor(Int32 keySize, CspParameters parameters, Boolean useDefaultKeySize)\r\n at System.Security.Cryptography.RSACryptoServiceProvider..ctor(CspParameters parameters)\r\n at Internal.Cryptography.Pal.CertificatePal.<>c.<GetRSAPrivateKey>b__61_0(CspParameters csp)\r\n at Internal.Cryptography.Pal.CertificatePal.GetPrivateKey[T](Func`2 createCsp, Func`2 createCng)\r\n at Internal.Cryptography.Pal.CertificatePal.GetRSAPrivateKey()\r\n at Internal.Cryptography.Pal.CertificateExtensionsCommon.GetPrivateKey[T](X509Certificate2 certificate, Predicate`1 matchesConstraints)\r\n at System.Security.Cryptography.X509Certificates.RSACertificateExtensions.GetRSAPrivateKey(X509Certificate2 certificate)\r\n at Microsoft.IdentityModel.Tokens.X509SecurityKey.get_PrivateKey()\r\n at Microsoft.IdentityModel.Tokens.X509SecurityKey.get_HasPrivateKey()\r\n at Microsoft.IdentityModel.Tokens.AsymmetricSignatureProvider.HasPrivateKey(SecurityKey key)\r\n at Microsoft.IdentityModel.Tokens.AsymmetricSignatureProvider..ctor(SecurityKey key, String algorithm, Boolean willCreateSignatures)\r\n at Microsoft.IdentityModel.Tokens.CryptoProviderFactory.CreateSignatureProvider(SecurityKey key, String algorithm, Boolean willCreateSignatures)\r\n at Microsoft.IdentityModel.Tokens.CryptoProviderFactory.CreateForSigning(SecurityKey key, String algorithm)\r\n at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.CreateEncodedSignature(String input, SigningCredentials signingCredentials)\r\n at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.WriteToken(SecurityToken token)\r\n at IdentityServer4.Services.DefaultTokenCreationService.CreateJwtAsync(JwtSecurityToken jwt) in C:\\local\\identity\\server4\\IdentityServer4\\src\\IdentityServer4\\Services\\DefaultTokenCreationService.cs:line 209\r\n at IdentityServer4.Services.DefaultTokenCreationService.<CreateTokenAsync>d__4.MoveNext() in C:\\local\\identity\\server4\\IdentityServer4\\src\\IdentityServer4\\Services\\DefaultTokenCreationService.cs:line 67\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at IdentityServer4.Services.DefaultTokenService.<CreateSecurityTokenAsync>d__9.MoveNext() in C:\\local\\identity\\server4\\IdentityServer4\\src\\IdentityServer4\\Services\\DefaultTokenService.cs:line 210\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at IdentityServer4.ResponseHandling.TokenResponseGenerator.<CreateAccessTokenAsync>d__14.MoveNext() in C:\\local\\identity\\server4\\IdentityServer4\\src\\IdentityServer4\\ResponseHandling\\TokenResponseGenerator.cs:line 313\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at IdentityServer4.ResponseHandling.TokenResponseGenerator.<ProcessAuthorizationCodeRequestAsync>d__10.MoveNext() in C:\\local\\identity\\server4\\IdentityServer4\\src\\IdentityServer4\\ResponseHandling\\TokenResponseGenerator.cs:line 133\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at IdentityServer4.ResponseHandling.TokenResponseGenerator.<ProcessAsync>d__7.MoveNext() in C:\\local\\identity\\server4\\IdentityServer4\\src\\IdentityServer4\\ResponseHandling\\TokenResponseGenerator.cs:line 88\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at IdentityServer4.Endpoints.TokenEndpoint.<ProcessTokenRequestAsync>d__7.MoveNext() in C:\\local\\identity\\server4\\IdentityServer4\\src\\IdentityServer4\\Endpoints\\TokenEndpoint.cs:line 98\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at IdentityServer4.Endpoints.TokenEndpoint.<ProcessAsync>d__6.MoveNext() in C:\\local\\identity\\server4\\IdentityServer4\\src\\IdentityServer4\\Endpoints\\TokenEndpoint.cs:line 70\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at IdentityServer4.Hosting.IdentityServerMiddleware.<Invoke>d__3.MoveNext() in C:\\local\\identity\\server4\\IdentityServer4\\src\\IdentityServer4\\Hosting\\IdentityServerMiddleware.cs:line 54","CategoryName":"IdentityServer4.Hosting.IdentityServerMiddleware"}}}}
Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware:Error: An unhandled exception has occurred: Keyset as registered is invalid
Internal.Cryptography.CryptoThrowHelper+WindowsCryptographicException: Keyset as registered is invalid
at Internal.NativeCrypto.CapiHelper.CreateProvHandle(CspParameters parameters, Boolean randomKeyContainer)
at System.Security.Cryptography.RSACryptoServiceProvider.get_SafeProvHandle()
at System.Security.Cryptography.RSACryptoServiceProvider.get_SafeKeyHandle()
at System.Security.Cryptography.RSACryptoServiceProvider..ctor(Int32 keySize, CspParameters parameters, Boolean useDefaultKeySize)
at System.Security.Cryptography.RSACryptoServiceProvider..ctor(CspParameters parameters)
at Internal.Cryptography.Pal.CertificatePal.<>c.<GetRSAPrivateKey>b__61_0(CspParameters csp)
at Internal.Cryptography.Pal.CertificatePal.GetPrivateKey[T](Func`2 createCsp, Func`2 createCng)
at Internal.Cryptography.Pal.CertificatePal.GetRSAPrivateKey()
at Internal.Cryptography.Pal.CertificateExtensionsCommon.GetPrivateKey[T](X509Certificate2 certificate, Predicate`1 matchesConstraints)
at System.Security.Cryptography.X509Certificates.RSACertificateExtensions.GetRSAPrivateKey(X509Certificate2 certificate)
at Microsoft.IdentityModel.Tokens.X509SecurityKey.get_PrivateKey()
at Microsoft.IdentityModel.Tokens.X509SecurityKey.get_HasPrivateKey()
at Microsoft.IdentityModel.Tokens.AsymmetricSignatureProvider.HasPrivateKey(SecurityKey key)
at Microsoft.IdentityModel.Tokens.AsymmetricSignatureProvider..ctor(SecurityKey key, String algorithm, Boolean willCreateSignatures)
at Microsoft.IdentityModel.Tokens.CryptoProviderFactory.CreateSignatureProvider(SecurityKey key, String algorithm, Boolean willCreateSignatures)
at Microsoft.IdentityModel.Tokens.CryptoProviderFactory.CreateForSigning(SecurityKey key, String algorithm)
at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.CreateEncodedSignature(String input, SigningCredentials signingCredentials)
at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.WriteToken(SecurityToken token)
at IdentityServer4.Services.DefaultTokenCreationService.CreateJwtAsync(JwtSecurityToken jwt) in C:\local\identity\server4\IdentityServer4\src\IdentityServer4\Services\DefaultTokenCreationService.cs:line 209
at IdentityServer4.Services.DefaultTokenCreationService.<CreateTokenAsync>d__4.MoveNext() in C:\local\identity\server4\IdentityServer4\src\IdentityServer4\Services\DefaultTokenCreationService.cs:line 67
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at IdentityServer4.Services.DefaultTokenService.<CreateSecurityTokenAsync>d__9.MoveNext() in C:\local\identity\server4\IdentityServer4\src\IdentityServer4\Services\DefaultTokenService.cs:line 210
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at IdentityServer4.ResponseHandling.TokenResponseGenerator.<CreateAccessTokenAsync>d__14.MoveNext() in C:\local\identity\server4\IdentityServer4\src\IdentityServer4\ResponseHandling\TokenResponseGenerator.cs:line 313
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at IdentityServer4.ResponseHandling.TokenResponseGenerator.<ProcessAuthorizationCodeRequestAsync>d__10.MoveNext() in C:\local\identity\server4\IdentityServer4\src\IdentityServer4\ResponseHandling\TokenResponseGenerator.cs:line 133
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at IdentityServer4.ResponseHandling.TokenResponseGenerator.<ProcessAsync>d__7.MoveNext() in C:\local\identity\server4\IdentityServer4\src\IdentityServer4\ResponseHandling\TokenResponseGenerator.cs:line 88
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at IdentityServer4.Endpoints.TokenEndpoint.<ProcessTokenRequestAsync>d__7.MoveNext() in C:\local\identity\server4\IdentityServer4\src\IdentityServer4\Endpoints\TokenEndpoint.cs:line 98
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at IdentityServer4.Endpoints.TokenEndpoint.<ProcessAsync>d__6.MoveNext() in C:\local\identity\server4\IdentityServer4\src\IdentityServer4\Endpoints\TokenEndpoint.cs:line 70
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at IdentityServer4.Hosting.IdentityServerMiddleware.<Invoke>d__3.MoveNext() in C:\local\identity\server4\IdentityServer4\src\IdentityServer4\Hosting\IdentityServerMiddleware.cs:line 54
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at IdentityServer4.Hosting.IdentityServerMiddleware.<Invoke>d__3.MoveNext() in C:\local\identity\server4\IdentityServer4\src\IdentityServer4\Hosting\IdentityServerMiddleware.cs:line 72
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.<Invoke>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Cors.Infrastructure.CorsMiddleware.<Invoke>d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at IdentityServer4.Hosting.BaseUrlMiddleware.<Invoke>d__3.MoveNext() in C:\local\identity\server4\IdentityServer4\src\IdentityServer4\Hosting\BaseUrlMiddleware.cs:line 43
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.<Invoke>d__6.MoveNext()
更多回答
If you've installed it into a cert store can you run certutil -silent -store my
and share the data for the cert (the specific one I want to know is the value for "Provider"). (certutil -user -silent -store my
if it's in CurrentUser\My instead of LocalMachine\My)
如果您已经将其安装到证书存储中,是否可以运行certutil-Silent-store my并共享证书的数据(我想知道的具体值是“提供者”的值)。(Certutil-User-Silent-如果位于CurrentUser\My而不是LocalMachine\My中,则存储My)
@bartonjs Here is the output: ------------- Serial Number: b3eeb248fd720d0e Issuer: CN=abaris.no NotBefore: 16.10.2018 16:25 NotAfter: 13.10.2028 16:25 Subject: CN=abaris.no Signature matches Public Key Root Certificate: Subject matches Issuer Cert Hash(sha1): bb 1a b6 b9 f8 1b 27 07 93 92 64 bc c5 90 c3 43 d2 62 72 9c Key Container = {700D6BDE-4203-418B-A353-0BFEABAC26A7} Provider = Microsoft Enhanced Cryptographic Provider v1.0 Missing stored keyset Encryption test passed -------------- It also says "Missing stored keyset".....
@bartonjs以下是输出:-序列号:b3eeb248fd720d0e颁发者:cn=abaris.no NotBetherBethering:16.10.2018 16:25 NotAfter:13.10.2028 16:25 Subject:cn=abaris.no签名匹配公钥根证书:Subject匹配颁发者证书哈希(Sha1):bb 1a b6 b9 f8 1b 27 07 07 93 92 64 bc c5 90 c3 43 d2 62 72 9c密钥容器={700D6BDE-4203-418B-A353-0BFEAB26A7}Provider=Microsoft Enhanced vProvider丢失密钥集加密测试通过
okay, the Enhanced provider should definitely load in CNG, but the native side agreeing the private key file is missing seems indicative. When you added it to the store you probably didn’t set PersistKeySey
and the key got deleted. For loading it from bytes, there must be some sort of key cloning going on which results in deleting the key before it gets loaded. If you re-import into the store after loading with PersistKeySet, the problem will likely go away.
好的,增强的提供商肯定应该在CNG中加载,但本地端同意私钥文件缺失似乎是指示性的。当您将其添加到存储中时,您可能没有设置PersistKeySey,因此密钥被删除。为了从字节加载它,必须进行某种类型的密钥克隆,从而导致在加载密钥之前将其删除。如果在加载PersistKeySet后重新导入到存储中,问题很可能会消失。
@bartonjs I have used different settings for X509KeyStorageFlags including PersistKeySet. When the Pfx is installed to X509Store(StoreName.My, StoreLocation.CurrentUser), I have verified that the private key is written to disk and that the process identity have read-write access to both folder and private key file. When pfx is installed in MMC the certificate UI states "You have a private key that corresponds to this certificate". I have not tried reimport as you suggests
@bartonjs我对X509KeyStorageFlagers使用了不同的设置,包括PersistKeySet。当PFX安装到X509Store(StoreName.My,StoreLocation.CurrentUser)时,我已经验证了私钥已写入磁盘,并且进程身份对文件夹和私钥文件都具有读写访问权限。当PFX安装在MMC中时,证书用户界面会显示“您有一个与此证书对应的私钥”。我没有像你建议的那样尝试重新进口
@bartonjs I have generated another certicate with makecert, and this certificate is now successfully loading with private keys with no changes to source code. Hence, it seems there is something with the certificate and pfx generated with OpenSSL. I am happy with using makecert for now even if it is officially deprecated.
@bartonjs我已经用makecert生成了另一个Certicate,这个证书现在成功地加载了私钥,而不需要更改源代码。因此,使用OpenSSL生成的证书和PFX似乎有些问题。我对目前使用makecert很满意,即使它已被正式弃用。
The problem was resolved by adding IIS_IUSR group.
From this link Add group IIS_IUSR:
已通过添加IIS_IUSR组解决此问题。从此链接添加组IIS_IUSR:
The problem was that the Permissions for the Private Key of the Certificate in the Windows Certificate Store did not have the IIS_IUSRS group set to allow read access.
问题是Windows证书存储中证书的私钥权限没有将IIS_IUSRS组设置为允许读取访问权限。
Right click certificate -> All Tasks -> Manage Private Keys -> Add group "IIS_IUSRS"
右键单击证书->所有任务->管理私钥->添加组“IIS_IUSRS”
I followed that blog post too and also had that issue.
The problem was when you run this to create PKCS12 file:
我也关注了这篇博客,也有这个问题。问题是当你运行这个来创建PKCS12文件时:
openssl pkcs12 -export -out example.pfx -inkey example.key -in example.crt -certfile example.crt
Try to remove -certfile example.crt
and it should work.
尝试删除-certfile example.crt,它应该可以工作。
Also according to .NET Core X509Certificate2 usage (under Windows/IIS, Docker, Linux) you can test if certificate was loaded from file correctly by accessing cert.PrivateKey
.
E.g.
此外,根据.NET Core X509cerficate2的用法(在Windows/IIS、Docker、Linux下),您可以通过访问cert.PrivateKey来测试是否从文件中正确加载了证书。例如。
X509Certificate2 cert = new X509Certificate2(Path.Combine(Directory.GetCurrentDirectory(), "cert.pfx"), "password");
Console.WriteLine("cert private key: " + cert.PrivateKey);
On IIS 10 I had to change my app pool identity to LocalSystem
在IIS 10上,我不得不将应用程序池标识更改为LocalSystem
Oh hey, that's my blog post! Glad to see that it's... well hopefully helping despite problems people run into. Speaking of which I have now run into this exception myself!
哦,嘿,那是我的博文!很高兴看到这是...嗯,希望能帮上忙,尽管人们会遇到一些问题。说到这里,我自己也遇到了这个例外!
My problem was that I created the certificate and tried to load it from disk using the new X509Certificate2(path, password)
syntax, but for some reason I had to import the cert into the registry on my development machine to stop the exception from occuring. I'm not actually sure why.
我的问题是,我创建了证书,并尝试使用新的X509证书2(路径,密码)语法从磁盘加载它,但由于某种原因,我不得不将证书导入到我的开发计算机上的注册表中,以阻止异常发生。我真的不确定为什么。
Make sure to import the certificate to the My/Personal
store of the CurrentUser
registry.
确保将证书导入到CurrentUser注册表的My/Personal存储中。
There are so many different answers on this thread, I hope one of them works for you, reader :)
在这个帖子上有这么多不同的答案,我希望其中一个对你有用,读者:)
In my case, which by the way wasn't an API but a class library, I just had to make sure I was running visual studio in admin mode and that this user I was opening the visual studio with, was the same one who had the certificate installed in the store/mmc. Reach out if any question.
在我的例子中,顺便说一句,它不是一个API,而是一个类库,我只需要确保我在管理员模式下运行的是Visual Studio,并且与我打开Visual Studio的用户是在存储/MMC中安装了证书的那个用户。如果有任何问题,请主动联系。
This issue was really bringing me grief because none of the above solutions were helping.
这个问题真的给我带来了悲痛,因为上面的解决方案都没有帮助。
Here's what it was:
https://improveandrepeat.com/2018/12/how-to-fix-the-keyset-does-not-exist-cryptographicexception/
它是这样的:https://improveandrepeat.com/2018/12/how-to-fix-the-keyset-does-not-exist-cryptographicexception/
I needed to go to mmc, add the Certificates snap-in, select the cert, go to All Tasks > Manage Private Keys, and add the IIS_IUSRS (or specific app pool if you prefer). I had tried doing something similar in certmgr.msc but for whatever reason the Manage Private Keys option was not available under All Tasks from that area.
我需要转到MMC,添加证书管理单元,选择证书,转到所有任务>管理私钥,然后添加IIS_IUSRS(如果愿意,也可以添加特定的应用程序池)。我曾尝试在certmgr.msc中执行类似的操作,但无论出于什么原因,在该区域的所有任务下都无法使用管理私钥选项。
On IIS application pools select the application then advanced settings and set Identity: Localsystem and Load user profile: true
在IIS应用程序池中,选择应用程序,然后选择高级设置并设置Identity:LocalSystem和Load User Profile:True
更多回答
In my case, my Application Pool Identity
is not IIS_IUSR, but this answer still solved my problem; adding the identity of the App Pool to the Permissions for the private key fixed it. Thank you!
在我的例子中,我的应用程序池标识不是IIS_IUSR,但这个答案仍然解决了我的问题;将应用程序池的标识添加到私钥的权限中解决了这个问题。谢谢!
This solution will vary and as @codeMonkey noted was a different application pool identity. Mine was a completely different app user. Check your app for more details - adding iis_usr might not work for you.
这个解决方案会有所不同,正如@codeMonkey所指出的,是一个不同的应用程序池标识。我是一个完全不同的应用程序用户。有关更多详细信息,请检查您的应用程序-添加iis_usr可能对您不起作用。
Adding IIS_IUSRS
group to certificate worked for me even if I have a different application pool identity. +1
将IIS_IUSRS组添加到证书对我有效,即使我具有不同的应用程序池标识。+1
We have had this problem for months and this fixed it. Thank you all.
我们已经有这个问题几个月了,这解决了它。谢谢大家。
@mihuilk you are a god among programmers, thank you!
@mihuilk你是程序员中的神,谢谢!
Why does this work? Removing -certfile example.crt
solved the problem. But it seems the pfx created is smaller without the last command, but with the last command, it does not contain a private key?
为什么这会奏效?删除-certfile Example.crt解决了问题。但是没有最后一个命令创建的PFX似乎更小,但是使用最后一个命令,它不包含私钥?
I'm not an expert, but as I understand -certfile file
options allows to add a chain of certificates (adds all certificates in that file to the .p12 store in addition to the input certificate)
我不是专家,但据我所知-certfile文件选项允许添加证书链(除了输入证书之外,还将该文件中的所有证书添加到.p12存储中)
我是一名优秀的程序员,十分优秀!