Skip to content

Instantly share code, notes, and snippets.

@caleb531
Last active March 11, 2020 18:58
Show Gist options
  • Save caleb531/3fe37bba0d220723b8913e52f1c3db45 to your computer and use it in GitHub Desktop.
Save caleb531/3fe37bba0d220723b8913e52f1c3db45 to your computer and use it in GitHub Desktop.
Scripts for creating and managing simple SSL certificates on macOS (useful for local HTTPS)
#!/usr/bin/env bash
cert_file="$1"
key_file="$2"
CERT_CONF="$(dirname "${BASH_SOURCE[0]}")"/cert-conf.cfg
if [ ! -f "$cert_file" ]; then
cert_hostname="$3"
# Generate proper self-signed SSL certificate with SAN field
# SAN field is required for Chrome >=58; see:
# <https://textslashplain.com/2017/03/10/chrome-deprecates-subject-cn-matching/>
/usr/local/opt/openssl/bin/openssl \
req \
-newkey rsa:2048 \
-sha256 \
-x509 \
-days 3650 \
-nodes \
-config <(cat "$CERT_CONF" | sed s/{hostname}/"$cert_hostname"/g) \
-out "$cert_file" \
-keyout "$key_file"
fi
# Add SSL certificate to macOS Keychain as a trusted certificate
sudo security \
add-trusted-cert \
-d \
-k /Library/Keychains/System.keychain \
"$cert_file"
# Self-signed SSL certificate template
# Source: <http://stackoverflow.com/a/27931596/560642>
[req]
prompt = no
distinguished_name = subject
req_extensions = req_ext
x509_extensions = x509_ext
string_mask = utf8only
[x509_ext]
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid,issuer
subjectAltName = @alternate_names
[req_ext]
subjectKeyIdentifier = hash
basicConstraints = CA:FALSE
keyUsage = digitalSignature, keyEncipherment
subjectAltName = @alternate_names
[subject]
commonName = {hostname}
[alternate_names]
DNS.1 = {hostname}
DNS.2 = www.{hostname}
#!/usr/bin/env bash
cert_file="$1"
key_file="$2"
if [ ! -f "$cert_file" ]; then
>&2 echo "Certificate file does not exist"
exit
fi
cert_fingerprint="$(openssl x509 \
-noout \
-fingerprint \
-sha1 \
-inform pem \
-in "$cert_file" \
| cut -d '=' -f 2 \
| grep -o '[0-9A-F]' \
| xargs \
| tr -d ' ')"
sudo security \
delete-certificate \
-Z "$cert_fingerprint" \
/Library/Keychains/System.keychain
# Keychain errors don't output trailing newlines; output one to reclaim
# readability
if [ $? != 0 ]; then
echo ''
fi
rm -f "$cert_file"
rm -f "$key_file"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment