.NET中的自签名证书,将签名算法从SHA-1更改为其他内容

时间:2017-08-26 20:55:41

标签: .net .net-core x509certificate x509certificate2

我得到了一个精彩的答案,关于创建一个自签名证书,由Azure主席在Generating self-signed certificate without external libraries 由优秀的bartonjs使用。

以下是Azure示例中提供的几乎所有代码。但是,我坚持认为签名算法怎么可以改变?它默认似乎是SHA-1,我可能错了,但也许应该明确地设置为SHA-256之类的东西。

public static X509Certificate2 CreateSelfSignedRsaCertificate(string subjectName, string friendlyName)
    {
        if(subjectName == null)
        {
            throw new ArgumentNullException(nameof(subjectName));
        }

        if(friendlyName == null)
        {
            throw new ArgumentNullException(nameof(friendlyName));
        }

        var keyParams = new CngKeyCreationParameters();
        keyParams.Parameters.Add(new CngProperty("Length", BitConverter.GetBytes(2048), CngPropertyOptions.Persist));
        using(var rsaKey = CngKey.Create(CngAlgorithm.Rsa, Guid.NewGuid().ToString(), keyParams))
        {
            using(RSA rsa = new RSACng(rsaKey))
            {
                var certRequest = new CertificateRequest(subjectName, rsa, HashAlgorithmName.SHA512, RSASignaturePadding.Pkcs1);

                //Explicitly not a CA.
                certRequest.CertificateExtensions.Add(new X509BasicConstraintsExtension(false, false, 0, false));

                certRequest.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature | X509KeyUsageFlags.KeyEncipherment, true));

                //TLS Server EKU.
                certRequest.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(new OidCollection { new Oid("1.3.6.1.5.5.7.3.1") }, false));

                //SubjectAlternativeName extension.
                var sanBuilder = new SubjectAlternativeNameBuilder();
                sanBuilder.AddDnsName("localhost");
                certRequest.CertificateExtensions.Add(sanBuilder.Build());

                DateTimeOffset now = DateTimeOffset.UtcNow;
                var certificate = certRequest.CreateSelfSigned(notBefore: now, notAfter: now.AddDays(1)/*now.AddDays(365.25)*/);
                certificate.FriendlyName = friendlyName;

                return certificate;
            }
        }
    }

0 个答案:

没有答案