简体   繁体   English

PrivateKey抛出了System.Security.Cryptography.CryptographicException类型的异常

[英]PrivateKey threw an exception of type System.Security.Cryptography.CryptographicException

I'm trying to use self-signed certificate using the following code: 我正在尝试使用以下代码使用自签名证书:

X509Certificate2 cert = ToCertificate("CN=localhost");


public static X509Certificate2 ToCertificate(this string subjectName,
                                                StoreName name = StoreName.My,
                                                StoreLocation location = StoreLocation.LocalMachine
                                                )
    {
        X509Store store = new X509Store(name, location);

        store.Open(OpenFlags.ReadOnly);

        try
        {
            var cert = store.Certificates.OfType<X509Certificate2>().FirstOrDefault(c => c.Subject.Equals(subjectName, StringComparison.OrdinalIgnoreCase));

            return cert != null ? new X509Certificate2(cert) : null;
        }
        catch (Exception)
        {

            throw;
        }
        finally
        {
            store.Certificates.OfType<X509Certificate2>().ToList().ForEach(c => c.Reset());
            store.Close();
        }
    }

I am getting the following exception: 我收到以下异常:

PrivateKey = 'cert.PrivateKey' threw an exception of type 'System.Security.Cryptography.CryptographicException'

在此输入图像描述

I Tried this fix , and this fix 我试过这个修复这个修复

But still having the problem! 但仍然有问题!

If you are debugging your application, try to open the Visual Studio as administrator. 如果要调试应用程序,请尝试以管理员身份打开Visual Studio。 It solved the problem for me. 它解决了我的问题。

Sounds like your certificate uses CNG key storage to store the private key. 听起来您的证书使用CNG密钥存储来存储私钥。 In this case, PrivateKey property will throw this exception when attempting to access the property. 在这种情况下, PrivateKey属性将在尝试访问该属性时抛出此异常。

In order to access the key properly, you have to use extension methods to access the key: https://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.x509certificate2(v=vs.110).aspx#Extension Methods 为了正确访问密钥,您必须使用扩展方法来访问密钥: https//msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.x509certificate2(v=vs.110 ).aspx#扩展方法

Moreover, these extension methods are preferred when accessing any private key storage type, either legacy (CSP) or CNG. 此外,当访问任何私钥存储类型(传统(CSP)或CNG)时,这些扩展方法是优选的。 That is, do not access PrivateKey and PublicKey properties directly, instead, access them via these methods. 也就是说,不要直接访问PrivateKeyPublicKey属性,而是通过这些方法访问它们。

davidchristiansen Said: davidchristiansen说:

What is a CNG Key? 什么是CNG钥匙? Certificates in Windows are stored using Storage Providers. Windows中的证书使用存储提供程序存储。 Windows has two of these providers, that are not compatible. Windows有两个这些提供程序,它们不兼容。 The old style “Cryptographic Service Providers” or CSP in short and the new style “Cryptography API: Next Generation” or CNG. 旧式“加密服务提供商”或简称CSP和新款“Cryptography API:Next Generation”或CNG。 The CNG providers have been around since Windows Vista, and although it is more secure and easier to use many facets of software are still not compatible with CNG providers. CNG提供商自Windows Vista以来一直存在,虽然它更安全,更易于使用,但软件的许多方面仍然与CNG提供商不兼容。 This appears to also include the .NET Framework. 这似乎还包括.NET Framework。

A possible workaround to this may be to use CryptoAPI/CNG API directly to deal with CNG keys. 可能的解决方法可能是直接使用CryptoAPI / CNG API来处理CNG密钥。 But if we want an easier and pure .NET solution which understands CNG, we need to find another solution (details to follow!). 但是,如果我们想要一个更容易理解CNG的纯粹.NET解决方案,我们需要找到另一个解决方案(详情请遵循!)。

I followed the following post to convert to convert my certificate key from CNG to RSA. 我按照以下帖子进行转换,将我的证书密钥从CNG转换为RSA。 It works! 有用!

http://blog.davidchristiansen.com/2016/05/521/ http://blog.davidchristiansen.com/2016/05/521/

Steps from blog: 博客的步骤:

  1. Extract your public key and full certificate chain from your PFX file 从PFX文件中提取公钥和完整证书链
  2. Extract the CNG private key 提取CNG私钥
  3. Convert the private key to RSA format 将私钥转换为RSA格式
  4. Merge public keys with RSA private key to a new PFX file 将具有RSA私钥的公钥合并到新的PFX文件

After changing your application to use the new PFX you just created, you should find that your issues have been resolved. 更改应用程序以使用刚刚创建的新PFX后,您应该发现问题已得到解决。

Now let's see how to carry out these steps using OpenSSL (Get OpenSSL for Windows from here) 现在让我们看看如何使用OpenSSL执行这些步骤(从这里获取OpenSSL for Windows)

  1. Extract your public key and full certificate chain from your PFX file 从PFX文件中提取公钥和完整证书链

OpenSSL pkcs12 -in "yourcertificate.pfx" -nokeys -out "yourcertificate.cer" -passin "pass:myreallystrongpassword" OpenSSL pkcs12 -in“yourcertificate.pfx”-nokeys -out“yourcertificate.cer”-passin“pass:myreallystrongpassword”

  1. Extract the CNG private key 提取CNG私钥

OpenSSL pkcs12 -in "yourcertificate.pfx" -nocerts –out “yourcertificate.pem" -passin "pass:myreallystrongpassword" -passout "pass:myreallystrongpassword" OpenSSL pkcs12 -in“yourcertificate.pfx”-nocerts -out“yourcertificate.pem”-passin“pass:myreallystrongpassword”-passout“pass:myreallystrongpassword”

  1. Convert the private key to RSA format 将私钥转换为RSA格式

OpenSSL rsa -inform PEM -in "yourcertificate.pem" -out "yourcertificate.rsa" -passin "pass:myreallystrongpassword" -passout "pass:myreallystrongpassword" OpenSSL rsa -inform PEM -in“yourcertificate.pem”-out“yourcertificate.rsa”-passin“pass:myreallystrongpassword”-passout“pass:myreallystrongpassword”

  1. Merge public keys with RSA private key to a new PFX file 将具有RSA私钥的公钥合并到新的PFX文件

OpenSSL pkcs12 -export -in "yourcertificate.cer" -inkey "yourcertificate.rsa" -out "yourcertificate-converted.pfx" -passin "pass:myreallystrongpassword" -passout "pass:myreallystrongpassword" OpenSSL pkcs12 -export -in“yourcertificate.cer”-inkey“yourcertificate.rsa”-out“yourcertificate-converted.pfx”-passin“pass:myreallystrongpassword”-passout“pass:myreallystrongpassword”

Running on IIS Express, the program uses your credentials to access the certificate, while on IIS the pool identity's credentials are used. 在IIS Express上运行,程序使用您的凭据访问证书,而在IIS上使用池身份的凭据。 You can easily check the certificate ACL to see who is allowed or not. 您可以轻松检查证书ACL以查看是否允许。

Follow these steps: 跟着这些步骤:

  1. Check what Application Pool your web site uses 检查您的网站使用的应用程序池

Open Internet Information Services Manager, select Sites in the Connections tree on the left. 打开Internet信息服务管理器,在左侧的“连接”树中选择“站点”。 Select your site in the middle panel and click Basic settings under Actions on the right panel. 在中间面板中选择您的站点,然后单击右侧面板上“操作”下的“基本设置”。

  1. Check what identity the Application Pool uses 检查应用程序池使用的标识

Select Application Pools in the Connections tree on the left and find the identity in the middle panel. 在左侧的Connections树中选择Application Pools,然后在中间面板中找到标识。 It'll be probably "NETWORK SERVICE". 它可能是“网络服务”。

  1. Add read permissions for the identity used by Application Pool to your certificate 将应用程序池使用的标识的读取权限添加到证书中

Open the Microsoft Management Console (mmc), add the Certificates snap-in for local Computer account and find your certificate under Personal certificates. 打开Microsoft管理控制台(mmc),为本地计算机帐户添加“证书”管理单元,并在“个人证书”下找到您的证书。 Open its context menu, All Tasks and Manage Private Keys.... Click Add.., enter the identity ("NETWORK SERVICE") and click Check Names and OK. 打开其上下文菜单,“所有任务”和“管理私钥”....单击“添加...”,输入标识(“网络服务”),然后单击“检查名称”和“确定”。 Under Permissions for allow only the Read permission. 在权限下,仅允许读取权限。

You can read details in this question: How to give ASP.NET access to a private key in a certificate in the certificate store? 您可以在此问题中阅读详细信息:如何让ASP.NET访问证书库中证书中的私钥?

refer: Certificate private key throws CryptographicException under IIS Web Server refer: 证书私钥在IIS Web服务器下抛出CryptographicException

暂无
暂无

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

相关问题 “System.Security.Cryptography.CryptographicException”类型的异常:密钥集不存在 - An exception of type 'System.Security.Cryptography.CryptographicException': keyset does not exist 类型System.Security.Cryptography.CryptographicException的第一次机会异常发生在System.Core.dll中 - A first chance exception of type 'System.Security.Cryptography.CryptographicException' occurred in System.Core.dll System.Security.Cryptography.CryptographicException:句柄无效 - System.Security.Cryptography.CryptographicException: The handle is invalid TwilioRequestValidator 中的瞬态 System.Security.Cryptography.CryptographicException - Transient System.Security.Cryptography.CryptographicException in TwilioRequestValidator System.Security.Cryptography.CryptographicException:参数不正确 - System.Security.Cryptography.CryptographicException: The parameter is incorrect System.Security.Cryptography.CryptographicException:'Cryptography_OAEPDecoding' - System.Security.Cryptography.CryptographicException: 'Cryptography_OAEPDecoding' System.Security.Cryptography.CryptographicException:系统找不到指定的文件 - System.Security.Cryptography.CryptographicException: The system cannot find the file specified 未处理的异常。 System.Security.Cryptography.CryptographicException:在密钥环中找不到密钥 {....} - Unhandled exception. System.Security.Cryptography.CryptographicException: The key {....} was not found in the key ring 引发异常:mscorlib.dll中的&#39;System.Security.Cryptography.CryptographicException&#39;其他信息:错误的数据 - Exception thrown: 'System.Security.Cryptography.CryptographicException' in mscorlib.dll Additional information: Bad Data SSL TCP SslStream 服务器抛出未处理的异常“System.Security.Cryptography.CryptographicException:找不到原始签名者” - SSL TCP SslStream Server throws unhandled exception “System.Security.Cryptography.CryptographicException: cannot find the original signer”
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM