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