您好,我想使用c#生成一个证书链。如下所示:

我为生成创建了以下代码:
using System;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
namespace CC.CertificateCore
{
public class CertBuilder
{
public static CertResult BuildChain()
{
CertResult result = new CertResult();
using ECDsa rootKey = ECDsa.Create(ECCurve.NamedCurves.brainpoolP256t1);
result.Root = CreateCert(rootKey, "CN=Root CA", "Root");
using ECDsa aKey = result.Root.GetECDsaPublicKey();
result.A = CreateCert(aKey, "CN=Root CA", "A");
using ECDsa bKey = result.A.GetECDsaPublicKey();
result.B = CreateCert(bKey, "CN=A CA", "B", selfSigned: true);
return result;
}
private static X509Certificate2 CreateCert(ECDsa key, string issuer, string friendlyName, bool selfSigned = false)
{
var distinguishedName = new X500DistinguishedName(issuer);
var request = new CertificateRequest(distinguishedName, key, HashAlgorithmName.MD5);
request.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature, false));
var certificate = selfSigned
? request.CreateSelfSigned(NotBefore(), NotAfter())
: request.Create(distinguishedName, X509SignatureGenerator.CreateForECDsa(key), NotBefore(), NotAfter(), Serial());
certificate.FriendlyName = friendlyName;
return certificate;
}
public static byte[] Serial()
{
byte[] serial = new byte[12];
using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
{
rng.GetBytes(serial);
}
return serial;
}
public static DateTimeOffset NotBefore()
{
return new DateTimeOffset(DateTime.UtcNow.AddDays(-1));
}
public static DateTimeOffset NotAfter()
{
return new DateTimeOffset(DateTime.UtcNow.AddDays(3650));
}
}
public class CertResult
{
public X509Certificate2 Root { get; set; }
public X509Certificate2 A { get; set; }
public X509Certificate2 B { get; set; }
}
}我得到了这个错误(WindowsCryptographicException:'Key I not exist.'):

我做错了什么?这条链条有可能吗?链是一种需求,我正在实现一个概念探针,以验证它是否可以做到。该项目是一个控制台项目netcore 3.1
提前谢谢你,
问候
发布于 2020-09-23 22:48:15
using ECDsa aKey = result.Root.GetECDsaPublicKey();
result.A = CreateCert(aKey, "CN=Root CA", "A");
...
: request.Create(distinguishedName, X509SignatureGenerator.CreateForECDsa(key), NotBefore(), NotAfter(), Serial());您正在尝试使用公钥签名。公钥不能签名。例外情况是密钥的私有部分丢失了。
由于您的代码最终使用与主题公钥和签名密钥相同的密钥,因此您将尝试将所有证书创建为自签名证书。通过对每个证书中的颁发者和主题使用相同的可分辨名称,可以加强这一点。所以根本就没有链式发生。
https://stackoverflow.com/questions/64027789
复制相似问题