4 # gencert - generate certificates
7 # ./gencert [-efh] [-D days] [-d destdir] hostname
10 # A simple script to generate self-signed X.509 certificates for
13 # The option are as follows:
14 # -D Specify the number of days the certificate
15 # will be valid for. Use 365 (a year) by default.
16 # -d Save the certificates to the given directory.
17 # By default the current directory is used.
18 # -e Use an EC key instead of RSA.
19 # -f Forcefully overwrite existing certificates
21 # -h Display usage and exit.
27 progname="$(basename -- "$0")"
30 echo "usage: $progname [-fh] [-d destdir] [-D days] hostname" >&2
31 echo "Please read the comment at the top of $0 for the usage." >&2
40 while getopts "D:d:efh" flag; do
43 d) destdir="${OPTARG%/}" ;;
51 shift $(($OPTIND - 1))
57 if [ ! -d "${destdir}" ]; then
58 echo "${progname}: ${destdir} is not a directory." >&2
63 pem="${destdir}/${hostname}.pem"
64 key="${destdir}/${hostname}.key"
66 if [ -f "$pem" -o -f "$key" ]; then
67 if [ $force = no ]; then
69 printf "Overwrite existing certificate $pem? [y/n] "
70 if ! read -r reply; then
75 [yY]) echo "overwriting"; break ;;
76 [nN]) echo "quitting"; exit 0 ;;
82 if [ $ec = yes ]; then
83 openssl ecparam -name secp384r1 -genkey -noout -out "${key}" && \
84 openssl req -new -x509 -key "${key}" -out "${pem}" -days "${days}" \
85 -nodes -subj "/CN=$hostname"
102 echo "Generated files:"
103 echo " $pem : certificate"
104 echo " $key : private key"