Skip to content

Instantly share code, notes, and snippets.

@JonathonReinhart
Created July 11, 2022 06:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JonathonReinhart/0bf74e6aca11b32f237c398c9a0f3bf3 to your computer and use it in GitHub Desktop.
Save JonathonReinhart/0bf74e6aca11b32f237c398c9a0f3bf3 to your computer and use it in GitHub Desktop.
Simply generate a self-signed certificate for a DNS name
#!/bin/bash
# Simply generate a self-signed certificate for a DNS name
# Options
NUMDAYS=3650 # 10 years
error() {
echo "Error: $1"
exit 1
}
# Process arguments
if [[ $# -lt 1 ]]; then
echo "Usage: $(basename $0) DNSNAME"
exit 1;
fi
dnsname="$1"
keyfile="${dnsname}.key"
crtfile="${dnsname}.crt"
test -f $keyfile && error "$keyfile already exists"
test -f $crtfile && error "$crtfile already exists"
# Find OpenSSL config file
sslconf="$OPENSSL_CONF"
if [ -z $sslconf ]; then
# Debian
sslconf="/etc/ssl/openssl.cnf"
fi
if [ ! -f $sslconf ]; then
# RedHat
sslconf="/etc/pki/tls/openssl.cnf"
fi
if [ ! -f $sslconf ]; then
error "Cannot find openssl.cnf"
fi
# Generate cert/key
openssl req -new -sha256 -x509 \
-newkey rsa:2048 -nodes -keyout "${keyfile}" \
-subj "/CN=${dnsname}" \
-days $NUMDAYS \
-extensions SAN \
-config <(cat $sslconf <(printf "\n[SAN]\nsubjectAltName=DNS:${dnsname}\n")) \
-out "${crtfile}" \
| exit $?
openssl x509 -noout -text -in "${crtfile}"
echo -e "\nSelf-signed cert written to ${crtfile}"
echo -e "Key written to ${keyfile}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment