Ana*_*ina 5 c# digital-certificate x509certificate2
我正在尝试使用以下代码使用自签名证书:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
我收到以下异常:
PrivateKey = 'cert.PrivateKey' threw an exception of type 'System.Security.Cryptography.CryptographicException'
Run Code Online (Sandbox Code Playgroud)
但是还是有问题!
大卫·克里斯蒂安森 说:
\n\n\n\n\n什么是 CNG 密钥?\n Windows 中的证书是使用存储提供程序存储的。Windows 有两个不兼容的提供程序。旧样式 \xe2\x80\x9cCryptography Service Providers\xe2\x80\x9d 或简称 CSP,新样式 \xe2\x80\x9cCryptography API:Next Generation\xe2\x80\x9d 或 CNG。CNG 提供程序自 Windows Vista 以来就已存在,尽管它更安全且更易于使用,但软件的许多方面仍然与 CNG 提供程序不兼容。这似乎还包括 .NET Framework。
\n\n一个可能的解决方法是直接使用 CryptoAPI/CNG API 来处理 CNG 密钥。但如果我们想要一个更简单、更纯粹的能够理解 CNG 的 .NET 解决方案,我们需要找到另一个解决方案(详细信息如下!)。
\n
我按照以下帖子进行转换,将我的证书密钥从 CNG 转换为 RSA。有用!
\n\nhttp://blog.davidchristiansen.com/2016/05/521/
\n\n博客步骤:
\n\n\n\n\n
\n\n- 从 PFX 文件中提取公钥和完整证书链\n
\n- 提取CNG私钥
\n- 将私钥转换为RSA格式
\n- 将公钥与 RSA 私钥合并到新的 PFX 文件
\n将应用程序更改为使用刚刚创建的新 PFX 后,\n 您应该会发现您的问题已得到解决。
\n\n现在让\xe2\x80\x99s 看看如何使用 OpenSSL 执行这些步骤(从此处获取适用于 Windows 的 OpenSSL\n)
\n\n\n
\n\n- 从 PFX 文件中提取公钥和完整证书链
\nOpenSSL pkcs12 -in "yourcertificate.pfx" -nokeys -out\n "yourcertificate.cer" -passin "pass:myreallystrongpassword"
\n\n\n
\n\n- 提取CNG私钥
\nOpenSSL pkcs12 -in "yourcertificate.pfx" -nocerts \xe2\x80\x93out\n \xe2\x80\x9cyourcertificate.pem" -passin "pass:myreallystrongpassword" -passout\n "pass:myreallystrongpassword"
\n\n\n
\n\n- 将私钥转换为RSA格式
\nOpenSSL rsa -inform PEM -in "yourcertificate.pem" -out\n "yourcertificate.rsa" -passin "pass:myreallystrongpassword" -passout\n "pass:myreallystrongpassword"
\n\n\n
\n\n- 将公钥与 RSA 私钥合并到新的 PFX 文件
\nOpenSSL pkcs12 -export -in "yourcertificate.cer" -inkey\n "yourcertificate.rsa" -out "yourcertificate-converted.pfx" -passin\n "pass:myreallystrongpassword" -passout "pass:myreallystrongpassword"
\n
| 归档时间: |
|
| 查看次数: |
11627 次 |
| 最近记录: |