Use OpenSSL to Create a Self-signed Certificate

March 11, 2024

Environment

OpenSSL 3.0 version in Ubuntu 22.04 LTS

Steps to Create Self-signed Certificate

create your CA (certificate authority)

  1. generate CA key
openssl genrsa -out ca.key 4096sh
  1. create CA cert file
openssl req -x509 -days 3650 -new -nodes -sha256 -key ca.key -out ca.crtsh

create server key and csr

  1. generate server.key
openssl genrsa -out server.key 2048sh
  1. generate csr file from server.key
openssl req -new -nodes -key server.key -out server.csrsh
You can also use below approach to combine step 1 and 2.
openssl req -new -nodes -keyout server.key -out server.csrsh

sign the csr by CA and output a server cert

TIP
If you need sign the csr with SAN (subject alternative name), you need create a file names server_v3.ext
authorityKeyIdentifier = keyid,issuer
basicConstraints = CA:FALSE
keyUsage = nonRepudiation, digitalSignature, keyEncipherment

subjectAltName = @alt_names

[alt_names]
DNS.1 = your.domain1.com
DNS.2 = your.domain2.com
IP.1 = 127.0.0.1
IP.2 = 192.168.0.1ext
If the top3 settings not suit for you, just find a sample in openssl default configuration file (normally it locate in /etc/ssl/openssl.cnf).
  1. CA sign the csr
If you don't want to set SAN, just ignore the -extfile server_v3.ext in below command.
openssl x509 -req -days 3650 -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out server_signed.crt -extfile server_v3.extsh

Convert Certificate to PKCS12-Formatted Keystore

Normally, we maybe want to use a PKCS12-formatted key store, so we can do this.
openssl pkcs12 -export -out server.p12 -inkey server.key -in server_signed.crtsh
The End