Skip to content

X509Certificate2/CommonCrypto: Exporting a certificate without a private key to a PKCS12 store with a password fails #23636

Description

@qmfrederik

If you have a X509Certificate2 object which represents a certificate without a private key, exporting that certificate to a Pkcs12 store will work on Windows and Linux but fails on Mac (which use CommonCrypto).

This is a regression on macOS as this worked with .NET Core 1.x (when using OpenSSL) and no longer works with .NET Core 2.0.

The following unit test reproduces the behavior:

using System;
using System.Security.Cryptography.X509Certificates;
using Xunit;

namespace temp
{
  public class UnitTest1
  {
    [Fact]
    public void Test1()
    {
      var cert = new X509Certificate2("my_cert.crt");
      var data = cert.Export(X509ContentType.Pkcs12, "password");
      Assert.NotNull(data);
    }
  }
}

The test passes on Windows & Linux but fails on macOS with the following error message:

Failed   certs.UnitTest1.Test1
Error Message:
 Interop+AppleCrypto+AppleCommonCryptoCryptographicException : One or more parameters passed to a function were not valid.
Stack Trace:
   at Interop.AppleCrypto.X509Export(X509ContentType contentType, SafeCreateHandle cfPassphrase, IntPtr[] certHandles)
   at Interop.AppleCrypto.X509ExportPfx(IntPtr[] certHandles, SafePasswordHandle exportPassword)
   at Internal.Cryptography.Pal.StorePal.AppleCertificateExporter.ExportPkcs12(SafePasswordHandle password)
   at Internal.Cryptography.Pal.StorePal.AppleCertificateExporter.Export(X509ContentType contentType, SafePasswordHandle password)
   at System.Security.Cryptography.X509Certificates.X509Certificate.Export(X509ContentType contentType, String password)
   at certs.UnitTest1.Test1() in /Users/quamotion/scratch/certs/UnitTest1.cs:line 13

my_cert.crt can be generated using the following script:

openssl genrsa -out my_key.key 2048
openssl req -new -key my_key.key -out my_request.csr
openssl x509 -req -days 3650 -in my_request.csr -signkey my_key.key -out my_cert.crt

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions