#!/bin/bash # # self-signed-cert # # Create a self-signed certificate for the common name passed # on the command line. # # How many bits should we use for the keys? # Default: the highest sane amount. NUM_BITS=4096 # For how long should the certificate be valid? # Default: 10 years. DAYS=3650 function usage() { echo "Usage: $0 [-p] [-b NUM_BITS] [-d DAYS] " echo '' echo ' The CN (common name) of the certificate. Used to name the output files.' echo '' echo '-p Combine the key/cert into a single PEM file.' echo "-b NUM_BITS Create keys of length NUM_BITS (default ${NUM_BITS})." echo "-d DAYS Create a certificate valid for DAYS days (default ${DAYS})." echo '' } # By default, don't create a PEM file. # Just leave the key/crt files as they are, separate. DO_PEM=0 # Some exit codes. EXIT_BAD_ARGS=1 EXIT_KEY_EXISTS=2 EXIT_CERT_EXISTS=3 while getopts "pb:d:" option; do case $option in p ) DO_PEM=1;; b ) NUM_BITS=$OPTARG;; d ) DAYS=$OPTARG;; * ) usage exit $EXIT_BAD_ARGS;; esac done # Get rid of the -p option if it was passed. shift $((OPTIND-1)) if [ $# -lt 1 ]; then usage exit $EXIT_BAD_ARGS fi CNAME=$1 KEYFILE=${CNAME}.key CERTFILE=${CNAME}.crt # Make sure the key/cert don't already exist before proceeding. if [ -f $KEYFILE ]; then echo "Key file $KEYFILE already exists. Bailing." exit $EXIT_KEY_EXISTS fi if [ -f $CERTFILE ]; then echo "Certificate file $CERTFILE already exists. Bailing." exit $EXIT_CERT_EXISTS fi # Generate the private key. openssl genrsa -out $KEYFILE $NUM_BITS # The private key needs to be kept secret. chmod 400 $KEYFILE # Generate the signed public key (certificate) using the private key. openssl req -new -x509 -nodes -sha1 -days $DAYS -key $KEYFILE -out $CERTFILE if [ $DO_PEM -eq 1 ]; then PEMFILE=${CNAME}.pem cat $CERTFILE $KEYFILE > $PEMFILE if [ $? -eq 0 ]; then # Only remove the key/cert files if we succeeded in combining # them. rm $KEYFILE rm $CERTFILE fi # This too must be kept secret, because it contains the private # key. chmod 400 $PEMFILE fi