Skip to content

Instantly share code, notes, and snippets.

@ThisIsNoahEvans
Last active March 19, 2023 21:40
Show Gist options
  • Save ThisIsNoahEvans/837263ef28630f134cc61f48509cca0e to your computer and use it in GitHub Desktop.
Save ThisIsNoahEvans/837263ef28630f134cc61f48509cca0e to your computer and use it in GitHub Desktop.
Generate self-signed cert for DNS name & add to macOS keychain

Generate a self-signed certifcate for a DNS name, and add it to the macOS Keychain as a trusted cert.

I wrote this in about 5 minutes - it is messy, it is badly coded, but it works for the purpose.

Just edit the domains array in the file to add the domain(s) you'd like to generate for.

#!/bin/bash
mkdir ~/local-ssl > /dev/null 2>&1
### ADD DOMAINS HERE ###
declare -a domains=( "" )
# Loop through the domains
for domain in "${domains[@]}"
do
cd ~/local-ssl
mkdir "$domain" && cd "$domain"
echo "
[req]
default_bits = 2048
distinguished_name = req_distinguished_name
req_extensions = req_ext
x509_extensions = v3_req
prompt = no
[req_distinguished_name]
countryName = XX
stateOrProvinceName = N/A
localityName = N/A
organizationName = Self-signed certificate
commonName = '$domain': Self-signed certificate
[req_ext]
subjectAltName = @alt_names
[v3_req]
subjectAltName = @alt_names
[alt_names]
DNS.1 = '$domain'" >> "ssl-config-$domain"
# Generate the cert
openssl req -x509 -nodes -days 730 -newkey rsa:2048 -keyout KEY-$domain.pem -out CERT-$domain.pem -config "ssl-config-$domain" > /dev/null 2>&1
echo "Generated certificate for $domain."
# Add to macOS keychain and trust
sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain CERT-$domain.pem
echo "Added to Keychain."
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment