How to create a valid, self-signed X509Certificate2 programmatically without loading from a file in .NET Core

I am currently using OpenSSL to create a PFX file. This causes an unwanted dependency, especially for Windows users. So I found some examples of how to create my own certificate using BouncyCastle, but this library is not compatible with .NET Core (or I could not find a compatible package).

So, is it possible to create a self-signed X509 certificate using only the .NET kernel to avoid dependence on OpenSSL (or any other certificate generating an external tool)?

EDIT: Someone (editor?) Suggested this question SO How to create a self-signed certificate using C #? gives an answer. Unfortunately, this has nothing to do with .NET Core. The accepted answer starts with This implementation uses the CX509CertificateRequestCertificate COM object (and friends - MSDN doc) from certenroll.dll to create a self signed certificate request and sign it, which is obviously NOT .NET Core ... In fact, none of the answers support .NET Core.

+11
source share
2 answers

, . API .Net Core 2.0. , , , " ", IIS.

    private X509Certificate2 buildSelfSignedServerCertificate()
    {
        SubjectAlternativeNameBuilder sanBuilder = new SubjectAlternativeNameBuilder();
        sanBuilder.AddIpAddress(IPAddress.Loopback);
        sanBuilder.AddIpAddress(IPAddress.IPv6Loopback);
        sanBuilder.AddDnsName("localhost");
        sanBuilder.AddDnsName(Environment.MachineName);

        X500DistinguishedName distinguishedName = new X500DistinguishedName($"CN={CertificateName}");

        using (RSA rsa = RSA.Create(2048))
        {
            var request = new CertificateRequest(distinguishedName, rsa, HashAlgorithmName.SHA256,RSASignaturePadding.Pkcs1);

            request.CertificateExtensions.Add(
                new X509KeyUsageExtension(X509KeyUsageFlags.DataEncipherment | X509KeyUsageFlags.KeyEncipherment | X509KeyUsageFlags.DigitalSignature , false));


            request.CertificateExtensions.Add(
               new X509EnhancedKeyUsageExtension(
                   new OidCollection { new Oid("1.3.6.1.5.5.7.3.1") }, false));

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

            var certificate= request.CreateSelfSigned(new DateTimeOffset(DateTime.UtcNow.AddDays(-1)), new DateTimeOffset(DateTime.UtcNow.AddDays(3650)));
            certificate.FriendlyName = CertificateName;

            return new X509Certificate2(certificate.Export(X509ContentType.Pfx, "WeNeedASaf3rPassword"), "WeNeedASaf3rPassword", X509KeyStorageFlags.MachineKeySet);
        }
    }

PFX, X509Certificate2 . pfx.

+9

Microsoft makecert pvk2pfx ( SDK), .net-. .net, .net , , .

, : https://msdn.microsoft.com/en-us/library/ff699202.aspx

: : .net(core).. .net, dll.

-3

Source: https://habr.com/ru/post/1672248/


All Articles