Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save deeco/26f28d0d2edbfbadefce332694dcba41 to your computer and use it in GitHub Desktop.
Save deeco/26f28d0d2edbfbadefce332694dcba41 to your computer and use it in GitHub Desktop.
Create Root CA and self-signed Certificate for local TLS testing.
#!/usr/bin/env bash
set -e
# Full Qualified Domain Name
FQDN="${1:-localhost.dev}"
FQDN="$(echo "${FQDN}" | tr 'A-Z' 'a-z')"
# Optional settings
COUNTRY="DE"
CITY="Berlin"
ORG_NAME="Local Testing"
ORG_UNIT="IT Geeks"
# Internal settings
CA_NAME="$(echo ${ORG_NAME} | tr 'A-Z' 'a-z' | sed 's/[^a-z0-9]+/_/g')"
# make directories to work from
mkdir -p certs/{ca,${FQDN}}
function create_root_ca() {
# Create your own Root Certificate Authority
openssl genrsa \
-out "certs/ca/${CA_NAME}_ca.key.pem" \
2048
# Self-sign your Root Certificate Authority
openssl req \
-x509 \
-new \
-nodes \
-days 3650 \
-key "certs/ca/${CA_NAME}_ca.key.pem" \
-out "certs/ca/${CA_NAME}_ca.crt.pem" \
-subj "/C=${COUNTRY}/L=${CITY}/O=${ORG_NAME}/OU=${ORG_UNIT}/CN=${ORG_NAME} CA"
}
function create_certificate() {
openssl genrsa \
-out "certs/${FQDN}.key.pem" \
2048
# Create the CSR to FQDN and *.FQDN
openssl req -new \
-key "certs/${FQDN}.key.pem" \
-out "certs/${FQDN}.csr.pem" \
-subj "/C=${COUNTRY}/L=${CITY}/O=${ORG_NAME}/OU=${ORG_UNIT}/CN=${FQDN}/CN=*.${FQDN}"
}
function sign_certificate() {
# Sign the request from Server with your Root CA
openssl x509 \
-req -in "certs/${FQDN}.csr.pem" \
-CA "certs/ca/${CA_NAME}_ca.crt.pem" \
-CAkey "certs/ca/${CA_NAME}_ca.key.pem" \
-CAcreateserial \
-out "certs/${FQDN}.cert.pem" \
-days 3650
# Remove the request
rm -f "certs/${FQDN}.csr.pem"
}
function bundle_certificate() {
echo "PRIVATE server bundle: certs/${FQDN}.bundle.pem"
echo " > keep it secret and safe - just as key.pem"
cat \
"certs/${FQDN}.key.pem" \
"certs/${FQDN}.cert.pem" \
> "certs/${FQDN}.bundle.pem"
echo "chain: certs/${FQDN}.chain.pem"
echo " > contains Intermediates and Root CA in least-authoritative first manner"
# if there were an intermediate, it would be concatonated before the Root CA
cat \
"certs/ca/${CA_NAME}_ca.crt.pem" \
> "certs/${FQDN}.chain.pem"
echo "fullchain: certs/${FQDN}.fullchain.pem"
echo " > contains Server CERT, Intermediates and Root CA"
cat \
"certs/${FQDN}.cert.pem" \
"certs/ca/${CA_NAME}_ca.crt.pem" \
> "certs/${FQDN}.fullchain.pem"
}
create_root_ca
create_certificate
sign_certificate
bundle_certificate
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment