Skip to content

Instantly share code, notes, and snippets.

@blamh
Created January 31, 2017 21:41
Show Gist options
  • Save blamh/626e45a7f201b6e755126efa8db8c234 to your computer and use it in GitHub Desktop.
Save blamh/626e45a7f201b6e755126efa8db8c234 to your computer and use it in GitHub Desktop.
Script for creating self signed ssl certs with alt names
#!/bin/bash
CERT_NAME="dev_cert"
TOP_DEV_DOMAIN="example.dev"
DOMAINS=(
"DNS:$TOP_DEV_DOMAIN"
"DNS:*.$TOP_DEV_DOMAIN"
"DNS:*.level2.$TOP_DEV_DOMAIN"
"DNS:*.level3.level2.$TOP_DEV_DOMAIN"
)
OPENSSL_CNF="/usr/local/etc/openssl/openssl.cnf"
ADD_TO_KEYCHAIN=true
if [ ! -e $CERT_NAME.key ]; then
echo "Generating a new private key"
openssl genrsa -out $CERT_NAME.key 2048
fi
if [ ! -e $OPENSSL_CNF ]; then
echo "Could not find $OPENSSL_CNF."
exit
fi
echo "Creating a custom openssl cnf file."
cp $OPENSSL_CNF /tmp/openssl_san.cnf
read -d '' CERT_BLOCK << EOF
[ server_cert_extensions ]
basicConstraints = CA:FALSE
nsCertType = server
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid,issuer:always
issuerAltName = issuer:copy
subjectAltName = \$ENV::SUBJECT_ALT_NAME_RAW
EOF
printf "\n$CERT_BLOCK\n" >> /tmp/openssl_san.cnf
function join_by { local IFS="$1"; shift; echo "$*"; }
SUBJECT_ALT_NAME_RAW="`join_by ", " "${DOMAINS[@]}"`"
echo "Creating a new certificate and signing it with the private key."
SUBJECT_ALT_NAME_RAW=$SUBJECT_ALT_NAME_RAW openssl req -new -x509 \
-subj "/C=DK/ST=NONE/L=Copenhagen/CN=$TOP_DEV_DOMAIN" \
-key $CERT_NAME.key \
-out $CERT_NAME.crt \
-days 365 \
-config /tmp/openssl_san.cnf \
-extensions server_cert_extensions
rm /tmp/openssl_san.cnf
# Write out the serial number of the cert. This can be used for checking the cert
# in the browser.
openssl x509 -in $CERT_NAME.crt -serial -noout
if [ $ADD_TO_KEYCHAIN ]; then
echo "Replaces the certificte in the keychain"
sudo security delete-certificate -c $TOP_DEV_DOMAIN
sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain $CERT_NAME.crt
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment