Skip to content

Instantly share code, notes, and snippets.

@efossas efossas/tls.sh
Created Mar 12, 2019

Embed
What would you like to do?
Script for generating TLS certificates
#!/bin/sh
#
# Generate tls certificates for https
#
print_usage() {
cat <<EOF
Usage: tls [flags...]
-p [directory path for files]
-n [name for files]
-d [domain name]
-e [days to expire]
-c [path to ca files]
-a optional, certificate authority files will be created instead
EOF
exit
}
DPATH=''
FNAME=''
DOMAIN=''
EXPIRE=''
CPATH=''
OPTION_CA='false'
while getopts 'p:n:d:e:c:a' flag; do
case "${flag}" in
p) DPATH="${OPTARG}" ;;
n) FNAME="${OPTARG}" ;;
d) DOMAIN="${OPTARG}" ;;
e) EXPIRE="${OPTARG}" ;;
c) CPATH="${OPTARG}" ;;
a) OPTION_CA='true' ;;
*) print_usage
exit 1 ;;
esac
done
# make sure all mandatory flags were set
if [[ -z $DPATH || -z $FNAME || -z $DOMAIN || -z $EXPIRE ]]; then
print_usage
elif [[ -z $OPTION_CA && -z $CPATH ]]; then
print_usage
fi
FPATH="${DPATH}/${FNAME}"
mkdir -p ./${DPATH}
if [ "$OPTION_CA" == 'true' ]; then
# generate certificate authority key and certificate (add -des3 to require a passphrase)
echo "\n@@ CERTIFICATE AUTHORITY: ${FNAME} ${DOMAIN}";
openssl genrsa -out ${FPATH}.key 4096;
openssl req -x509 -new -nodes -key ${FPATH}.key -sha256 -days ${EXPIRE} -out ${FPATH}.crt -subj "/CN=${DOMAIN}" -extensions v3_ca;
else
# generate key (private rsa key)
echo "\n@@ PRIVATE KEY: ${FNAME} ${DOMAIN}"
openssl genrsa -out ${FPATH}.key 4096
# generate csr (certificate signing request)
echo "\n@@ CERTIFICATE SIGNING REQUEST: ${FNAME} ${DOMAIN}"
openssl req -new -sha256 -key ${FPATH}.key -out ${FPATH}.csr -subj "/CN=${DOMAIN}"
# generate ext (subject alternate names extension file)
echo "\n@@ EXTENSIONS: ${FNAME} ${DOMAIN}"
cat <<EOF > ${FPATH}.ext
authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = @alt_names
[alt_names]
DNS.1 = ${DOMAIN}
EOF
# generate crt (tls certificate)
echo "\n@@ CERTIFICATE: ${FNAME} ${DOMAIN}"
openssl x509 -req -in ${FPATH}.csr -CA ${CPATH}.crt -CAkey ${CPATH}.key -CAcreateserial -out ${FPATH}.crt -days ${EXPIRE} -sha256 -extfile ${FPATH}.ext
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.