2

Convert .crt, .csr, and .key files to .pfx or .p12 using powershell on Windows server 2016.

I have .cert, .csr, and .key files. But in order to execute the "netsh http add sslcert ..." command, I need the .pfx or .p12 file. And I need this to be done in powershell. Openssl is not an option.

I have accomplished the above using openssl. But Im restricted from downloading software now, so thats not an option any more. Im looking for equivalent of openssl pkcs12 -export -out domain.name.pfx -inkey key.key -in cert.crt command in powershell.

naoumm
  • 69
  • 1
  • 1
  • 5
  • 1
    Expressing a need is not the same as asking a question. What have you tried so far, and with what results? – Bill_Stewart Jul 31 '19 at 16:56
  • I think this is more of question about Windows tools rather than Powershell. There may be Windows system command line tools to do this, but I strongly doubt standard Powershell will include anything specific. – John Rees Aug 02 '19 at 13:46

2 Answers2

4

This is an old thread but since I was stuck on the exact same problem and finally found the correct answer that wasn't just everyone shouting to use openssl which sometimes isn't available I thought I'd share here for the next lucky soul.

There is a built-in windows utility call CertUtil which can be called from PS and will do exactly this. It's available out of the box at least as far back as server 2012, cant' speak to older versions.

certutil –MergePFX certfile.cer certfile.pfx

A couple things to keep in mind, the -MergePFX only prompts for the certfile not the key so:

  • Private key file must have .KEY extension.
  • Cert and key files must have the same base file name.
  • Cert and key file must be in the same directory.
0

If you can use .NET Core 3.0:

  • Load the certificate via cert = new X509Certificate2(certFile)
  • If the keyfile is PEM encoded (e.g. starts with "----- BEGIN ") then load it, remember what type it is (human or software), find the base64 contents between the header and footer, and run that through Convert.FromBase64String to get the BER/DER encoded format of the key.
  • key = RSA.Create()
  • key.ImportPkcs8PrivateKey(bytes, out _), key.ImportEncryptedPkcs8PrivateKey(password, bytes, out _), or key.ImportRSAPrivateKey(bytes, out _); depending on what format the private key file is in.
  • certWithKey = cert.CopyWithPrivateKey(key)
  • File.WriteAllBytes("new.pfx", certWithKey.Export(X509ContentType.Pkcs12, password))

If you can use .NET Core 2.1 / .NET Framework 4.7.2:

If you're stuck on something older:

You could try loading the cert, manually loading the key into an RSACryptoServiceProvider, using cert.set_PrivateKey, and exporting that. Only works on .NET Framework (eliminated from .NET Core because it has too many side effects, especially when done to a cert already in a persisted certificate store).

bartonjs
  • 30,352
  • 2
  • 71
  • 111