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

1,960 views
Skip to first unread message

Nathan Youngman

unread,
Dec 9, 2015, 8:39:50 PM12/9/15
to golang-nuts

I have a newbie crypto question using Go's tls and x509 packages. Feels like I'm missing something.


Thanks.

Wim Lewis

unread,
Dec 9, 2015, 10:46:17 PM12/9/15
to golang-nuts

On Dec 9, 2015, at 5:39 PM, Nathan Youngman <junk...@nathany.com> wrote:
> I have a newbie crypto question using Go's tls and x509 packages. Feels like I'm missing something.

As I understand it, tls.Certificate is slightly misleadingly named. It holds a set of certificates and some supplementary info- the kind of thing you'd get from a TLS server in its hello message.

I think you'd want to just wrap up your certificate and related data into the struct:

parsedPrivateKey, parsedCert, err := pkcs12.Decode(...)

thing := tls.Certificate{
Certificate: [][]byte{ parsedCert.Raw },
PrivateKey: parsedPrivateKey,
Leaf: parsedCert,
}

The "Raw" field of an x509.Certificate is the whole certificate, DER-encoded (which is just the result of base64-decoding the PEM certificate). And if you're only doing verification I assume you don't need to set the PrivateKey field of tls.Certificate.


Nathan Youngman

unread,
Dec 16, 2015, 1:24:21 PM12/16/15
to golang-nuts

Thanks Wim. Your code sample works perfectly and you taught me more about the difference between PEM and DER.

My only remaining concern is that I may not be doing some of the checks that X509KeyPair() does, but I'm not going to worry for now.

Nathan.
Reply all
Reply to author
Forward
0 new messages