Skip to content

Instantly share code, notes, and snippets.

@whereisaaron
Created August 4, 2022 09:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save whereisaaron/efc05cd4a4c464c439620b9f9d7d1a1b to your computer and use it in GitHub Desktop.
Save whereisaaron/efc05cd4a4c464c439620b9f9d7d1a1b to your computer and use it in GitHub Desktop.
Create a self-signed certificate using openssl to bootstrap a server
#!/bin/bash
set -eu
#
# Create a self-signed certificate to bootstrap a server
# Ref: https://devopscube.com/create-self-signed-certificates-openssl/
#
if [ "$#" -ne 1 ]
then
echo "Error: No domain name argument provided"
echo "Usage: Provide a domain name as an argument"
exit 1
fi
DOMAIN=$1
cert_file_prefix="self-signed"
temp_dir=$(mktemp -d)
#
# Create root CA & Private key
#
openssl req \
-x509 \
-sha256 \
-days 356 \
-nodes \
-newkey rsa:2048 \
-subj "/CN=${DOMAIN}/C=NZ/L=Wellington" \
-keyout rootCA.key -out rootCA.crt
#
# Generate Private key
#
openssl genrsa -out ${cert_file_prefix}.key 2048
#
# Create csf conf
#
cat > ${temp_dir}/csr.conf <<EOF
[ req ]
default_bits = 2048
prompt = no
default_md = sha256
req_extensions = req_ext
distinguished_name = dn
[ dn ]
C = NZ
ST = Wellington
L = Wellington
O = Outwide
OU = Internet
CN = ${DOMAIN}
[ req_ext ]
subjectAltName = @alt_names
[ alt_names ]
DNS.1 = ${DOMAIN}
IP.1 = 127.0.0.1
EOF
#
# create CSR request using private key
#
openssl req -new -key ${cert_file_prefix}.key -out ${temp_dir}/${cert_file_prefix}.csr -config ${temp_dir}/csr.conf
#
# Create a external config file for the certificate
#
cert_conf_file=$(mktemp)
cat > ${temp_dir}/cert.conf <<EOF
authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = @alt_names
[alt_names]
DNS.1 = ${DOMAIN}
EOF
#
# Create cert with self signed CA
#
openssl x509 -req \
-in ${temp_dir}/${cert_file_prefix}.csr \
-CA rootCA.crt \
-CAkey rootCA.key \
-CAcreateserial \
-CAserial ${temp_dir}/rootCA.srl \
-out ${cert_file_prefix}.crt \
-days 365 \
-sha256 \
-extfile ${temp_dir}/cert.conf
#
# Clean up
#
rm -rf ${temp_dir}
#
# Output
#
echo "Self-signed root and cert files:"
echo ""
ls -1 rootCA.{crt,key} ${cert_file_prefix}.{crt,key}
#end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment