Converting PFX format to PEM via OpenSSL programmatically
I run into a task that I needed to do in Go, given a PFX file, I needed to get a tls.X509KeyPair from that. However, Go doesn’t have support for PFX. RavenDB makes extensive use of PFX in general, so that made things hard for us. I looked into all sorts of options, but I couldn’t find any way to manage that properly. The nearest find was the pkcs12 package, but that has support for only some DER format, and cannot handle common PFX files. That was a problem.
Luckily, I know how to use OpenSSL, but while there are countless examples on how to use OpenSSL to convert PFX to PEM and the other way around, all of them assume that you are using that from the command line, which isn’t what we want. It took me a bit of time, but I cobbled together a one off code that does the work. The code has a strange shape, I’m aware, because I wrote it to interface with Go, but it does the job.
Now, from Go, I can run the following:
As you can see, most of the code is there to manage error handling. But you can now convert a PFX to PEM and then pass that to X509keyPair easily.
That said, this seems just utterly ridiculous to me. There has got to be a better way to do that, surely.
Btw, both PFX and single PEM container file might contain more that one certificate (e.g. intermediate certificate and/or the private key) which I don't see how it's handled here.
Using something like
cat certificate.crt intermediates.pem private.key > ssl-certs.pemand then
bind *:443 ssl crt ssl-certs.pemis very common in haproxy setup for instance.
Yes, I'm making some assumptions about the kind of certificates that I'm getting here. If needed, the changes to support multiple items aren't that complex