x509certificate2.net-standard-2.0

Create a certificate request using .netstandard 2.0 library


NetStandard 2.0 apparently does not include `System.Security.Cryptography.X509Certificates.CertificateRequest'.

So is it not possible to create X509Certificates in a .NETStandard 2.0 library? If not, why not? X509Certificates are included so it seems an odd exclusion.


Solution

  • .NET Standard 2.0 was built between .NET Framework 4.6.1 and 4.6.2, and doesn't have types that weren't present in .NET Framework 4.6.2.

    CertificateRequest was added to .NET Framework in 4.7.2.

    The easiest answer is to target either .NET Framework or .NET Core instead of .NET Standard, then the type will become available (provided you use a high enough version). Alternatively, unless you're using a custom X509SignatureGenerator, the type is simple enough that you could bind it with reflection.

    private static X509Certificate2 MakeCert(string certDN, RSA key)
    {
        Type certificateRequestType = typeof(RSACertificateExtensions).Assembly.
            GetType("System.Security.Cryptography.X509Certificates.CertificateRequest");
    
        object request = certificateRequestType.GetConstructor(
            new[] { typeof(string), typeof(RSA), typeof(HashAlgorithmName), typeof(RSASignaturePadding) }).Invoke(
            new object[] { certDN, key, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1 });
    
        Collection<X509Extension> extensions = (Collection<X509Extension>)
            certificateRequestType.GetProperty("CertificateExtensions").GetValue(request);
    
        // add things to the extensions collection
        ...
    
        DateTimeOffset now = DateTimeOffset.UtcNow;
    
        return (X509Certificate2)certificateRequestType.GetMethod("CreateSelfSigned").Invoke(
            new object[] { now.AddMinutes(-5), now.AddDays(30) });
    }