Search code examples
.netpowershell.net-corex509x509certificate2

Translating a OpenSSL p12 creation command to Powershell and/or .NET Core 2.0


Before breaking my head, I thought about the community (maybe this would be useful in general), how could the following be translated to Powershell and/or .NET Core 2.0?

openssl pkcs12 -export -out p12file.p12 -inkey privatekeygenerateinsomeportal.pem -in clientcertificatedownloadedfromsomeportal.pem

I definitely don't know how to do it in .NET Core 2.0 (hints here) and I haven't yet found the appropriate Powershell spell either. It appears Windows facilities have not supported pem format, which makes this a tad difficult (hence .NET Core 2.0 to rescue?), like extracted from How to convert a PFX to .PEM format? Or how to generate a .PEM file? Using Native/Standard Windows tool

Windows do not support PEM format

Or there are some third party libraries, as demontrated here.

It also feels there can be subtleties in the .p12 format that cause interoperability problems (say, when the result would be used in various environments via Xamarin.Forms and whatnot).


Solution

  • Assuming that what you want to do is:

    • Load a certificate from a file
    • Load a private key from a file
    • Save them together in one PFX

    Then the only part that .NET Core can't do for you easily is loading the private key. If you can figure out how to get the key (from RSAParameters or a live object, or whatever) you can do

    using (var cert = new X509Certificate2("cert.pem"))
    using (var mated = cert.CopyWithPrivateKey(key))
    {
        return mated.Export(X509ContentType.Pfx, password);
    }
    

    And presumably File.WriteAlllBytes that value.

    CopyWithPrivateKey is new in Core 2.0, and requires compiling with the netcoreapp20 TFM.

    Loading key files is on the ToDo list for .NET: https://github.com/dotnet/corefx/issues/20414