In this article we’ll cover creating and signing x509 Certificates in Golang. This exercise can be a helpful reference if you’re writing integration tests for web services which should test HTTPS functionality, or otherwise working on certificate handling code.
Create a Certificate Authority
In this article we’ll create and manage our own Certificate Authority (CA) locally to keep the examples here simple. Working with CAs locally will help prepare you for working with other public certificate authorities later.
Let’s get started by creating a CA which will be used to sign all of our certificates using the x509 package from the Go Standard Library:
Note that the field IsCA
is set to true
above indicating this certificate is a CA certificate.
We’ll generate a private key for the CA:
And create the certificate:
We’ll PEM Encode our certificate and private key for signing other certificates in upcoming steps:
Now we’re ready to use this CA.
Generate & Signing a Certificate
The next exercise is to create a certificate which our CA will sign:
Note that in the above example the certificate we’ve created contains:
IPAddresses: []net.IP{net.IPv4(127, 0, 0, 1), net.IPv6loopback},
This option will make our certificate valid over localhost
for local network testing.
Create a private key for the certificate:
Sign the certificate with the previously created CA:
PEM Encode the certificate:
At this point the certificate is ready to be deployed on a local HTTPS server.
WebServer Configuration
Now that we have a certificate to use (and a CA which has signed it to ensure trust from the client to the server) we’ll deploy our new certificate to a webserver provided by the httptest package.
Start by creating a Key Pair which will be used for the server configuration:
And a CertPool to house our certificate for client connections:
Next we’ll create a tls.Config which will be provided to our server:
Finally, start the httptest.Server:
Now we’re ready to connect to our server.
Connecting to the Server
Now that we know how to start the server it’s time to test the connection to it. We’ll use the standard client from the net/http package.
We’ll start by creating the tls.Config needed for the client to communicate properly with the server using our certificate:
We’ll define an http.Transport and create the http.Client:
Finally we’ll make a GET request to the server:
When it’s working properly the http.Request body contains success!
Demo Program
In the above sections we worked through the individual steps that build up to implementation in complete applications, but if you’re looking for a working example of all these pieces put together see this demo program available on GitHub:
Happy coding!
Originally published at https://shaneutt.com.