Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to turn an x509.Certificate into a tls.Certificate in Go?

I'm using x/crypto/pkcs12 to load a DER formatted *.p12 file. There is an example in the documentation that uses tls.X509KeyPair to make a tls.Certificate which can be used for an HTTP client.

That's perfect, and works fine. But then I also want to verify that the certificate hasn't expired. The pkcs12 library also has a Decode function which returns an x509 certificate, that I can than use the Verify method on. This also works fine.

It just seems odd to me that I'm decoding the DER twice. Once for an x509.Certificate to verify, and again to get a tls.Certificate. I don't know the relationship between these two Certificate structures, but seeing as the tls package has a function named tls.X509KeyPair that takes some bytes, shouldn't there also be an obvious way to get a tls.Certificate from an x509.Certificate or visa versa? What am I missing?

like image 337
nathany Avatar asked Dec 10 '15 01:12

nathany


1 Answers

A tls.Certificate often stores a certificate chain - in other words, > 1 certificate. Notice its Certificate field is of type [][]byte, where each certificate is a []byte.

The tls package imports the x509 package, so there isn't a function in x509 to get a tls.Certificate; that would cause an import cycle. But if you have an x509.Certificate, you already have a tls.Certificate; just put the x509.Certificate's Raw bytes into a tls.Certificate's Certificate slice.

like image 165
Matt Avatar answered Oct 01 '22 13:10

Matt