Skip to content

Instantly share code, notes, and snippets.

@elcharitas
Created February 21, 2024 08:08
Show Gist options
  • Save elcharitas/8af4159b36ec855346f433ffa5317dd3 to your computer and use it in GitHub Desktop.
Save elcharitas/8af4159b36ec855346f433ffa5317dd3 to your computer and use it in GitHub Desktop.
Generate Local SSL cert and Host file on macOS
#!/bin/bash
# This script generates a self-signed certificate for a local development server on macOS
# It is inspired by https://github.com/matt-goldman/local-signin-with-apple for windows powershell
# Default URL and certificate password
url="local-dev.com"
certPassword=""
# Check for root privileges
if [ "$(id -u)" != "0" ]; then
echo "This script needs to be run with root privileges. Please rerun this script as root."
exit 1
fi
# Parse command line arguments for URL and certPassword
while getopts ":u:p:" opt; do
case ${opt} in
u ) url=$OPTARG
;;
p ) certPassword=$OPTARG
;;
\? ) echo "Usage: ./local-dev.sh [-u] <url> [-p] <certPassword>"
;;
esac
done
# Generate a random password if not specified
if [ -z "$certPassword" ]; then
certPassword=$(openssl rand -base64 12)
fi
# Directory to store generated certificates
certFolderPath="$HOME/.applesignin"
mkdir -p "$certFolderPath"
# File paths
pemFilePath="$certFolderPath/$url.pem"
keyFilePath="$certFolderPath/$url.key"
pfxFilePath="$certFolderPath/$url.pfx"
crtFilePath="$certFolderPath/$url.crt"
echo "🔒 Generating certificate for $url"
openssl req -newkey rsa:4096 -nodes -keyout "$keyFilePath" -x509 -days 365 -out "$pemFilePath" -subj "/CN=$url" -addext "subjectAltName = DNS:$url"
openssl pkcs12 -export -out "$pfxFilePath" -inkey "$keyFilePath" -in "$pemFilePath" -password pass:"$certPassword"
openssl pkcs12 -in "$pfxFilePath" -out "$crtFilePath" -clcerts -nokeys -password pass:"$certPassword"
echo "✅ Done"
echo "🔒 Importing certificate to keychain"
security import "$pfxFilePath" -k ~/Library/Keychains/login.keychain-db -P "$certPassword" -T /usr/bin/codesign -A
echo "✅ Done"
# Adding URL to hosts file
hostsLine="127.0.0.1 $url"
read -p "Do you want to add $url to your hosts file? (y/N) " confirmation
if [[ "$confirmation" =~ ^[Yy]$ ]]; then
echo "📝 Adding entry to hosts file"
echo "$hostsLine" | sudo tee -a /etc/hosts
echo "✅ Done"
else
echo "Skipping adding $url to hosts file"
echo "You will need to manually add this hosts entry to your hosts file:"
echo "$hostsLine"
fi
echo "Local developer certificates for https://$url have been generated and installed."
echo "The certificate password is: $certPassword"
echo
echo "You should be able to access your dev server at https://$url"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment