如何在.NET Core中生成对CSR的响应(即编写CSR签名服务器)?

时间:2018-07-01 12:26:56

标签: .net .net-core x509certificate2

我正在通过Nuget软件包System.Security.Cryptography.Cng了解有关证书签名请求和服务器签名的信息。还有什么比尝试重新创建更好的方法。我似乎无法绕开一个障碍,那就是服务器签名方,即在下面的代码中,我在using子句的System.InvalidOperationException: 'An X509Extension with OID '2.5.29.37' has already been specified.'中获得了request.Create(。我在http://oid-info.com/get/2.5.29.37看到了有关扩展密钥使用的信息。

问题:

  1. MakeLocalhostCert可能是错误的,应该进行哪些更改以使其成为签署CSR的证书?
  2. 是否可以在要返回的CSR中添加/删除扩展名/ OID?我相信是的,但是这部分内容目前使我难以理解。

为了达到这一目标,我在https://stackoverflow.com/users/6535399/bartonjshttps://stackoverflow.com/a/45240640/1332416使用了https://stackoverflow.com/a/44073726/1332416的出色答案。 :)

    private static void CsrSigningTest()
    {
        //Both ECDSA and RSA included here, though ECDSA is probably better.
        using(ECDsa privateClientEcdsaKey = ECDsa.Create(ECCurve.NamedCurves.nistP256))
        //using(RSA privateClientRsaKey = RSA.Create(2048))
        {
            //A client creates a certificate signing request.
            CertificateRequest request = new CertificateRequest(
                new X500DistinguishedName("CN=example.com, O=Example Ltd, OU=AllOver, L=Sacremento, ST=\"California\", C=US, E=some@example.com"),
                privateClientEcdsaKey,
                HashAlgorithmName.SHA256);
            /*CertificateRequest request = new CertificateRequest(
                new X500DistinguishedName("CN=example.com, O=Example Ltd, OU=AllOver, L=Sacremento, ST=\"California\", C=US, E=some@example.com"),
                privateClientRsaKey,
                HashAlgorithmName.SHA256,
                RSASignaturePadding.Pkcs1);*/

            var sanBuilder = new SubjectAlternativeNameBuilder();
            sanBuilder.AddDnsName("example.com");
            request.CertificateExtensions.Add(sanBuilder.Build());

            //Not a CA, a server certificate.
            request.CertificateExtensions.Add(new X509BasicConstraintsExtension(false, false, 0, false));
            request.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(new OidCollection { new Oid("1.3.6.1.5.5.7.3.1") }, false));
            request.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(new OidCollection { new Oid("1.3.6.1.5.5.7.3.8") }, false));

            byte[] derEncodedCsr = request.CreateSigningRequest();
            var csrSb = new StringBuilder();
            csrSb.AppendLine("-----BEGIN CERTIFICATE REQUEST-----");
            csrSb.AppendLine(Convert.ToBase64String(derEncodedCsr));
            csrSb.AppendLine("-----END CERTIFICATE REQUEST-----");

            //Thus far OK, this csr seems to be working when using an online checker.
            var csr = csrSb.ToString();

            //Now, sending this to a server... How does the server function:
            //1) Read the CSR to be processed?
            //2) How does this CSR get signed?
            //In the following, can the signing cert be self-signed could be had from
            //https://stackoverflow.com/a/45240640/1332416

            byte[] serial = new byte[16];
            using(var rng = RandomNumberGenerator.Create())
            {
                rng.GetBytes(serial);
            }

            DateTimeOffset notBefore = DateTimeOffset.UtcNow;
            DateTimeOffset notAfter = notBefore.AddYears(1);
            var issuerCertificate = MakeLocalhostCert();
            //For the part 1) there, this doesn't seem to work, likely since CSR isn't a X509 certificate.
            //But then again, there doesn't seem to be anything in CertificateRequest to read this.
            //In reality in the server the prologue and epilogue strings should be removed and the string read.
            //var testRequest = new X509Certificate2(derEncodedCsr);
            using(X509Certificate2 responseToCsr = request.Create(issuerCertificate, notBefore, notAfter, serial))
            {
                //How to add extensions here?
                var csrResSb = new StringBuilder();
                csrResSb.AppendLine("-----BEGIN CERTIFICATE-----");
                csrResSb.AppendLine(Convert.ToBase64String(responseToCsr.GetRawCertData()));
                csrResSb.AppendLine("-----END CERTIFICATE-----");

                var signedCert = csrResSb.ToString();
            }
        }
    }

    private static X509Certificate2 MakeLocalhostCert()
    {
        using(ECDsa key = ECDsa.Create(ECCurve.NamedCurves.nistP384))
        {
            var request = new CertificateRequest(
                "CN=localhost",
                key,
                HashAlgorithmName.SHA384);

            request.CertificateExtensions.Add(
                new X509BasicConstraintsExtension(true, false, 0, true));

            const X509KeyUsageFlags endEntityTypicalUsages =
                X509KeyUsageFlags.DataEncipherment |
                X509KeyUsageFlags.KeyEncipherment |
                X509KeyUsageFlags.DigitalSignature |
                X509KeyUsageFlags.NonRepudiation |
                X509KeyUsageFlags.KeyCertSign;

            request.CertificateExtensions.Add(
                new X509KeyUsageExtension(endEntityTypicalUsages, true));

            var sanBuilder = new SubjectAlternativeNameBuilder();
            sanBuilder.AddDnsName("localhost");
            sanBuilder.AddIpAddress(IPAddress.Loopback);
            sanBuilder.AddIpAddress(IPAddress.IPv6Loopback);

            request.CertificateExtensions.Add(sanBuilder.Build());

            /*request.CertificateExtensions.Add(
                new X509EnhancedKeyUsageExtension(
                    new OidCollection
                    {
                // server and client authentication
                new Oid("1.3.6.1.5.5.7.3.1"),
                new Oid("1.3.6.1.5.5.7.3.2")
                    },
                    false));*/

            DateTimeOffset now = DateTimeOffset.UtcNow.AddMinutes(-1);

            return request.CreateSelfSigned(now, now.AddYears(2));
        }
    }

:一旦我应用了有关OID的修复程序并将最后一位更改为

using(X509Certificate2 responseToCsr = request.Create(issuerCertificate, notBefore, notAfter, serial))
            {
                request.CertificateExtensions.Add(new X509SubjectKeyIdentifierExtension(issuerCertificate.PublicKey, false));
                var csrResSb = new StringBuilder();
                csrResSb.AppendLine("-----BEGIN CERTIFICATE-----");
                csrResSb.AppendLine(Convert.ToBase64String(responseToCsr.Export(X509ContentType.Cert), Base64FormattingOptions.InsertLineBreaks));
                csrResSb.AppendLine("-----END CERTIFICATE-----");

                var signedCert = csrResSb.ToString();
            }

我在signedCert中取回了一个看起来像已签名的CSR的证书。如果从实际的CSR文件中读取,缺少的部分将是构建CSR。

CoreFx GH中存在一个问题,跟踪此处涉及的一些问题:Security crypto - Roadmap

1 个答案:

答案 0 :(得分:1)

要解决您的异常,您要使代码设置一个带有两个目的OID的EKU扩展,而不是两个带有一个目的OID的扩展。

// Defined two EKU extensions
request.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(new OidCollection { new Oid("1.3.6.1.5.5.7.3.1") }, false));
request.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(new OidCollection { new Oid("1.3.6.1.5.5.7.3.8") }, false));

// One extension carrying multiple purpose OIDs
request.CertificateExtensions.Add(
    new X509EnhancedKeyUsageExtension(
        new OidCollection
        {
            new Oid("1.3.6.1.5.5.7.3.1"),
            new Oid("1.3.6.1.5.5.7.3.8"),
        },
        false));

然后您的标题/问题中还有两个其他问题:

  • “如何在.NET Core中生成对CSR的响应(即编写CSR签名服务器)?”
    • 此代码未读取CSR,因此未响应。
      • 该类的目的是为了满足单元测试和其他开发环境的需求,并能够生成CSR以发送给实际的CA产品。
      • .NET Core甚至无法读取CSR,只需编写它们即可。
  • “我正在通过Nuget包System.Security.Cryptography.Cng了解有关证书签名请求和签名服务器的信息”
    • 您的代码似乎都不使用Cng类型(这很好,您应该很少在乎)。 CertificateRequest是System.Security.Cryptography.X509Certificates.dll的一部分,该文件通过Microsoft.NETCore.App公开
  • “是否可以在要返回的CSR中添加/删除扩展名/ OID?”
    • 是的,您可以在调用CreateSigningRequest之前将它们添加到CertificateExtensions属性中。
  • (暗示)“是否可以在要返回的证书中添加/删除扩展名/ OID?”
    • 是的,您可以在调用CreateCreateSelfSigned之前将它们添加到CertificateExtensions属性中。