Skip to content

Instantly share code, notes, and snippets.

@samcofer
Created June 3, 2024 20:01
Show Gist options
  • Save samcofer/ba73d094df1e6b7eb6331d4e898a7ab5 to your computer and use it in GitHub Desktop.
Save samcofer/ba73d094df1e6b7eb6331d4e898a7ab5 to your computer and use it in GitHub Desktop.
Script to generate a self-signed certificate in bash
#!/bin/bash
# Check if URL is passed as an argument
if [ $# -eq 0 ]; then
echo "Error: Please provide a URL as an argument."
exit 1
fi
# Set the URL
URL=$1
# Generate a private key for the CA
openssl genrsa -out my_ca.key 2048
# Create a self-signed certificate for the CA
openssl req -new -x509 -key my_ca.key -out my_ca.crt -days 365 -subj "/CN=My Local CA"
# Generate a private key
openssl genrsa -out $URL.key 2048
# Create a configuration file for the certificate
cat <<EOF >$URL.cnf
[ req ]
prompt = no
default_bits = 2048
distinguished_name = req_distinguished_name
req_extensions = req_ext
[ req_distinguished_name ]
countryName = US
stateOrProvinceName = California
localityName = San Francisco
organizationName = Example Inc.
commonName = $URL
[ req_ext ]
subjectAltName = @alt_names
[alt_names]
DNS.1 = $URL
DNS.2 = www.$URL
EOF
# Generate a Certificate Signing Request (CSR)
openssl req -new -key $URL.key -out $URL.csr -config $URL.cnf
# Sign the CSR with the local CA
openssl x509 -req -in $URL.csr -CA my_ca.crt -CAkey my_ca.key -CAcreateserial -out $URL.crt -days 365 -sha256
echo "Certificate signed by local CA for $URL has been generated:"
ls -l $URL.*
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment