Instantly share code, notes, and snippets.

@rdev5 /generate-csr.sh Secret
Created Jun 4, 2018

Embed
What would you like to do?
#!/bin/bash
# Note:
# - This script prefers AES256 over 3DES for password protecting private keys (https://stackoverflow.com/a/3938726)
# - This script may be used to renew certificates if a copy of the private key is made locally available in the format name_domain_ext.key
FILENAME="$1"
SUBJ="$2"
KEYSIZE="$3"
OPENSSL_CNF=""
if [ -z "$OPENSSL_CNF" ]; then
if [ -f "/etc/pki/tls/openssl.cnf" ]; then
OPENSSL_CNF="/etc/pki/tls/openssl.cnf"
fi
if [ -f "/etc/ssl/openssl.cnf" ]; then
OPENSSL_CNF="/etc/ssl/openssl.cnf"
fi
if [ -z "$OPENSSL_CNF" ]; then
echo "Failed to determine path to openssl.cnf. Please ensure the file exists or set this variable manually (OPENSSL_CNF)."
exit 1
fi
fi
if [ -z "$FILENAME" ] || [ -z "$SUBJ" ]; then
echo "Usage: $0 <names.dat> <subject.dat> [keysize]"
exit 1
fi
while IFS='' read -r line || [[ -n "$line" ]]; do
[ -z "$line" ] && continue
IFS=':' read -ra line <<< "$line"
CN="${line[0]}"
IFS=',' read -ra names <<< "${line[1]}"
DNS_LIST="DNS:${CN}"
i=2
for name in "${names[@]}"; do
[ "${name}" == "${CN}" ] && continue
DNS_LIST="${DNS_LIST},DNS:${name}"
((i++))
done
ALIAS=$(echo "${CN}" | tr . _)
SUBJECT="${SUBJ}/CN=${CN}"
KEYFILE="${ALIAS}.key"
CSRFILE="${ALIAS}.csr"
if [ ! -f "$KEYFILE" ]; then
if [ -z "$KEYSIZE" ] || [ "$KEYSIZE" -lt 2048 ]; then
echo "[WARN] Weak key size specified (increased to 2048-bit)"
KEYSIZE=2048
fi
openssl genrsa -aes256 -out "$KEYFILE" "$KEYSIZE"
chmod 0400 "$KEYFILE"
fi
echo "Generating CSR: ${CN} ($CSRFILE)"
openssl req -new -key "$KEYFILE" \
-subj "$SUBJECT" \
-reqexts SAN \
-config <(cat "$OPENSSL_CNF" <(printf "\n[SAN]\nsubjectAltName=${DNS_LIST}")) \
-out "$CSRFILE"
done < "$FILENAME"
dns.example.com:example.com,dns.example.com,dns1.example.com,dns2.exmaple.com
/emailAddress=identity@example.com/C=US/ST=State Name/L=City Name/O=Company Name/OU=Department Name
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment