Skip to content

Instantly share code, notes, and snippets.

@OnnoGabriel
Last active October 31, 2020 20:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save OnnoGabriel/f717192ed92bf55725337358f4af5ab2 to your computer and use it in GitHub Desktop.
Save OnnoGabriel/f717192ed92bf55725337358f4af5ab2 to your computer and use it in GitHub Desktop.
Create self-signed CA certificates and certificates for local domains
#!/bin/bash
# Creates self-signed CA certificates and certificates for local domains.
#
# Prompts for a local domain name (e.g. my-app.localhost) and creates all
# necessary certificates.
#
# Next steps:
# Copy the certificates (e.g. my-app.localhost.crt and my-app.localhost.key) to
# your service (Nginx, Apache, ...) and configure it.
# Import the CA certificates in your browsers settings (e.g. my-app.localhost.rootCA.crt).
# Your country code
COUNTRY=DE
# Your state
STATE=Berlin
# Your organization. This will appear in the list of trusted CAs in your browser.
ORGANIZATION=DCD
# Check if openssl is installed
if [ ! -x "$(command -v openssl)" ]; then
echo 'Error: openssl is not installed.' >&2
exit 1
fi
read -p "Please enter the local domain name: " DOMAIN
# Check if the root CA file is already created
CANAME="rootCA"
if [ ! -f "$CANAME.crt" ]; then
echo "CA file \"$CANAME.crt\" does not exist. Create root key and certificate..."
openssl genrsa -out $CANAME.key 4096 # or with pw protection: openssl genrsa -des3 -out $CANAME.key 4096
openssl req -x509 -new -nodes -subj "/C=$COUNTRY/ST=$STATE/O=$ORGANIZATION/CN=$ORGANIZATION" -key $CANAME.key -sha256 -days 1024 -out $CANAME.crt
fi
# Create Certificates
echo "Create file $DOMAIN.key..."
openssl genrsa -out $DOMAIN.key 2048
echo "Create file $DOMAIN.csr..."
openssl req -new -sha256 -key $DOMAIN.key -subj "/C=$COUNTRY/ST=$STATE/O=$ORGANIZATION/CN=$DOMAIN" -out $DOMAIN.csr
echo "Create and sign file $DOMAIN.crt..."
# Create config file
cat >$DOMAIN.v3.ext<<EOF
authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = @alt_names
[alt_names]
DNS.1 = $DOMAIN
EOF
# Create and sign certificate (valid for 500 days)
openssl x509 -req -in $DOMAIN.csr -CA $CANAME.crt -CAkey $CANAME.key -CAcreateserial -out $DOMAIN.crt -days 1024 -sha256 -extfile $DOMAIN.v3.ext
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment