Skip to content

Instantly share code, notes, and snippets.

@sturadnidge
Last active March 21, 2023 09:38
Show Gist options
  • Save sturadnidge/71cc9dbfbf1965faa4e6 to your computer and use it in GitHub Desktop.
Save sturadnidge/71cc9dbfbf1965faa4e6 to your computer and use it in GitHub Desktop.
Generate a self signed certificate in 1 line + a config file

To generate a self-signed cert, do the following:

openssl req -config 12factor.req -new -nodes -x509 -newkey rsa:2048 -sha256 -keyout 12factor.key -out 12factor.cert -days 3650

Where 12factor.req is:

[ req ]
default_bits        = 2048
default_keyfile     = 12factor.key
distinguished_name  = subject
req_extensions      = req_ext
x509_extensions     = x509_ext
string_mask         = utf8only
prompt              = no

[ subject ]
countryName         = AU
stateOrProvinceName = NSW
localityName        = Sydney
organizationName    = Pivotal
commonName          = 12factor.com
emailAddress        = admin@12factor.com

# Section x509_ext is used when generating a self-signed certificate.
[ x509_ext ]
subjectKeyIdentifier    = hash
authorityKeyIdentifier  = keyid,issuer
basicConstraints        = CA:FALSE
keyUsage                = digitalSignature, keyEncipherment
subjectAltName          = @alternate_names
nsComment               = "OpenSSL Generated Certificate"
extendedKeyUsage        = serverAuth, clientAuth

# Section req_ext is used when generating a certificate signing request.
[ req_ext ]
subjectKeyIdentifier = hash
basicConstraints     = CA:FALSE
keyUsage             = digitalSignature, keyEncipherment
subjectAltName       = @alternate_names
nsComment            = "OpenSSL Generated Certificate"
extendedKeyUsage     = serverAuth, clientAuth

[ alternate_names ]
DNS.1 = 12factor.com
DNS.2 = *.12factor.com

Then to combine things to get a .pem

cat 12factor.key 12factor.cert > 12factor.pem

Then to extract the public key for use in validation

openssl x509 -pubkey -noout -in 12factor.pem > 12factor.pub

@sturadnidge
Copy link
Author

sturadnidge commented Jun 20, 2018

Alternatively, one line without a config file courtesy of https://letsencrypt.org/docs/certificates-for-localhost/

openssl req -x509 -out localhost.cert -keyout localhost.key \ -newkey rsa:2048 -nodes -sha256 \ -subj '/CN=localhost' -extensions EXT -config <( \ printf "[dn]\nCN=localhost\n[req]\ndistinguished_name = dn\n[EXT]\nsubjectAltName=DNS:localhost\nkeyUsage=digitalSignature\nextendedKeyUsage=serverAuth")

You can then configure your local web server with localhost.cert and localhost.key, and install localhost.cert in your list of locally trusted roots.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment