证书链X509

Certificate chain X509

您好,我想使用 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 does not exist.'):

我做错了什么?这条链甚至可能吗?链条是一项要求,我正在实施概念探索以验证它是否可以完成。 该项目是控制台项目 netcore 3.1

提前致谢,

此致

using ECDsa aKey = result.Root.GetECDsaPublicKey();

result.A = CreateCert(aKey, "CN=Root CA", "A");

...

 : request.Create(distinguishedName, X509SignatureGenerator.CreateForECDsa(key), NotBefore(), NotAfter(), Serial());

您正在尝试使用 public 密钥进行签名。 Public 密钥无法签名。异常是说密钥的私有部分丢失。

由于您的代码最终使用与主题 public 密钥和签名密钥相同的密钥,因此您正在尝试将所有证书创建为 self-signed。您在每个证书中为颁发者和主题使用相同的专有名称可以加强这一点。所以根本没有链接发生。