【发布时间】:2021-03-09 06:07:19
【问题描述】:
使用 .NET Core 3.1 和 BouncyCastle
我有一个来自 Pkcs12 的私有 ECC 密钥。请问如何将其存储在 X509Certificate2 私钥中?
我之所以这样尝试,是因为当我将 Pkcs12 加载为 X509Certificate2 时,X509Certificate2.PrivateKey 方法会抛出“未实现/算法不支持异常”。
这是我目前所拥有的:
using var stream = new MemoryStream(myPkcs12);
Pkcs12Store pstore = new Pkcs12Store(stream, password.ToCharArray());
var name = "";
foreach (string alias in store.Aliases)
{
if (pstore.IsKeyEntry(alias))
{
name = alias;
}
}
var key = pstore.GetKey(name);
var cert = new X509Certificate2(myPkcs12, "mypassword", X509KeyStorageFlags.EphemeralKeySet | X509KeyStorageFlags.Exportable);
cert.PrivateKey = // key? I imagine it is incorrect to use DotNetUtilities.ToRSA()?
谢谢!
更新:
发这个帖子的原因是因为这个问题:
private const string EccTestCert = "MIINbQIBAzCCDSkGCSqGSIb3DQEHAaCCDRoEgg0WMIIN.... 9wQUpQgYbgB7yknIW7Oaz3hogAVihJoCAgfQ";
var cert = new X509Certificate2(Convert.FromBase64String(EccTestCert), "1");
// If you inspect it, the PrivateKey throws an exception. Whilst with an RSA cert, it will not.
【问题讨论】:
-
PKCS#12 包含证书和私钥。因此,当使用
new X509Certificate2(myPkcs12...)导入 pkcs12 时,该实例是带有私钥的证书 - 因此您可以使用它进行签名或解密。 -
@DanielFisherlennybacon 嗨,当我尝试使用 ECC 证书进行此操作时,X509Certificate 无法返回 PrivateKey 供我使用。我将更新一个示例 Pkcs12。
标签: c# .net cryptography certificate bouncycastle