Created
March 12, 2019 00:32
-
-
Save efossas/59d38ab9ba8f33f94c94e6fa879c15bb to your computer and use it in GitHub Desktop.
Script for generating TLS certificates
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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