The simplest way to create a self-signed certificate is to use OpenSSL with the following one-liner:
openssl req -x509 -newkey rsa:4096 -sha256 -days 365 -nodes \
-keyout key.pem -out cert.pem -subj "/CN=localhost"It is often useful to create a single .pem file containing both the key and the cert:
cat key.pem cert.pem > self-signed.pemThese steps also work on Windows, except that you will need to use openssl.exe and type to concatenate the files:
type key.pem cert.pem > self-signed.pemThis resulting .pem file can be used by a webserver to provide HTTPS, but will generally result in web browsers being reluctant to display the resulting webpages, precisely because the certificate is self-signed. It is easy enough to click through the sequence of warning dialogue boxes that browsers present the user with and get the browser to accept the certificate. Sometimes however, users would prefer to explicitly trust the certificate and avoid the ominous red warning signs that browsers typically decorate the address bar with when rendering pages encrypted with the certificate (see next question).
Some browsers, notably Chrome, are more demanding of the certificate and require further structure; most versions of OpenSSL need directives provided via a configuration file to create this structure. For example, a configuration file self-signed.conf with the following content:
[req]
default_bits = 4096
distinguished_name = req_distinguished_name
x509_extensions = v3_req
prompt = no
[req_distinguished_name]
CN = localhost
[v3_req]
basicConstraints = CA:FALSE
keyUsage = digitalSignature, keyEncipherment
subjectAltName = @alt_names
[alt_names]
DNS.1 = localhost
IP.1 = 127.0.0.1can be provided to OpenSSL via the -config option:
openssl req -x509 -newkey rsa:4096 -sha256 -days 365 -nodes \
-keyout key.pem -out cert.pem -config self-signed.confThe resulting certificate carries a subjectAltName, which is what Chrome requires; a certificate identified only by its common name is rejected regardless of whether it is trusted.
Note: this content is a digest of several answers provided in this StackOverflow thread.