Test Certificates for localhost

While answering a couple of Stack Overflow questions recently I needed to create some certificates to use with localhost so I thought I’d record the steps to I would have something to link to next time.

Generate CA cert

$ openssl genrsa -out ca.key 2048
$ openssl req -new -x509 -days 365 -key ca.key \ 
  -subj "/C=GB/ST=Gloucestershire/O=localhost CA/CN=locahost Root CA" \
  -out ca.pem

Generate Server cert

$ openssl req -newkey rsa:2048 -nodes -keyout server.key \
  -subj "/C=GB/ST=Gloucestershire/O=Localhost CA/CN=localhost" \
  -out server.csr
$ openssl x509 -req \
  -extfile <(printf "subjectAltName=DNS:localhost,IP:127.0.0.1,IP:::1") \
  -days 365 -in server.csr -CA ca.crt -CAkey ca.key \
  -CAcreateserial -out server.pem

The outputs are

  • ca.key the private key for the CA
  • ca.pem the CA certificate
  • server.key the private key for the server
  • server.pem the certificate fro the server

Traditionally the certificates Subject’s CN value has contained the hostname of the machine the certificate is representing. But the spec doesn’t actually assign any specific meaning to this field and it was deprecated as part of RFC2818.

v3 of the x509 spec adds an extension for storing hostnames and IP addresses called Subject Alternative Names (known as SAN). The last line in the instructions adds SANs for the hostname localhost and the IP addresses 127.0.0.1 and ::1. This means it should be valid for all possible ways of accessing localhost.