Emmie
Emmie

Reputation: 796

C# Export X509Certificate2 to PFX including extensions

I am creating a X509Certificate2 in .NET Core 3 and would like to export this to a pfx file. The export is succeeding, however I also add extensions to the certificate, which are included in de certificate and visible in the debugger, but when I validate the exported pfx with openssl, there are no extensions added. If I just export the certificate to a crt file, and validate it with openssl, it does include the extensions. I also tried to use openssl to create a pfx file from the crt and key file, however that also does not include the extensions. How can I get a pfx with the extensions included?

I simplified the code for reading purpose.

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

    request.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature | X509KeyUsageFlags.NonRepudiation | X509KeyUsageFlags.KeyCertSign | X509KeyUsageFlags.CrlSign, false));
    request.CertificateExtensions.Add(new X509QcStatmentExtension(parameters.Roles, parameters.CertificateType, parameters.RetentionPeriod, parameters.NcaName, parameters.NcaId, false));
            
    var sanBuilder = new SubjectAlternativeNameBuilder();
    sanBuilder.AddDnsName(issuerDnsName);
    request.CertificateExtensions.Add(sanBuilder.Build());

    using (RSA issuerRSA = RSA.Create(4096))
    {
      var serialNumber = StringToByteArray(parameters.SerialNumber);
      var certificate = request.Create(issuerDN, X509SignatureGenerator.CreateForRSA(issuerRSA, RSASignaturePadding.Pkcs1), DateTimeOffset.Now, DateTimeOffset.Now.AddMonths(parameters.ExpirationInMonths), serialNumber);
      
      byte[] pkcs12 = certificate.Export(X509ContentType.Pfx, "password");
      var path = Path.GetTempPath();
      File.WriteAllBytes($"{path}generatedCert.pfx", pkcs12);
    }
}

The openssl commands I used are:

try and convert with openssl

openssl pkcs12 -export -out certificate.pfx -inkey qseal-certificate.key -in qseal-certificate.crt

Verify pfx certificate

openssl pkcs12 -info -in VanLanschotSandboxSigningCertificate.pfx

Verify crt certificate

openssl x509 -text -noout -in qseal-certificate.crt

Upvotes: 1

Views: 746

Answers (1)

bartonjs
bartonjs

Reputation: 33088

The extensions are there, the command just doesn't print them (it only shows the subject/issuer; then gives the full PEM-encoded certificate).

To see them, you need to actually print the certificate. If there's only one in the PFX you can accomplish this via

openssl pkcs12 -info -in VanLanschotSandboxSigningCertificate.pfx | openssl x509 -text

Upvotes: 1

Related Questions