James McDonald

Function for bash or zsh to generate SSL requests and certificates

Rather than memorising annoying OpenSSL options, stick this in your profile, edit the ‘SUBJ’ bit, and you’ll be generating keys with ease.

# Generate an SSL key and a signing request or self-signed certificate
sslcert() {
    cn=$1

    # The prefix for the certificate's subject, eg
    # SUBJ="/C=GB/ST=Edinburgh/L=Edinburgh/O=Widget Co"
    SUBJ="<<< SET THIS BIT >>>"

    if [ -z "$cn" -o "$cn" = "-h" ]; then
        echo "usage: $0 <common name> [csr|crt]" >&2
        echo "  csr - generate a certificate signing request (default)" >&2
        echo "  crt - generate a self-signed certificate" >&2
        return 1
    fi

    type=${2:-csr}

    name=$(echo $cn | sed -e 's/^\*\./star./')
    if [ -r $name ]; then
        echo "$0: $name already exists"
        return 1
    fi
    mkdir $name
    if [ $? -ne 0 ]; then
        echo "$0: can't mkdir $name" >&2
        return 1
    fi
    cd $name
    openssl genrsa -out ${name}.key 4096
    case $type in
    csr)
        openssl req -new -key ${name}.key -out ${name}.csr -sha256 -subj "${SUBJ}/CN=${cn}"
        ;;
    crt)
        openssl req -new -x509 -days 3650 -key ${name}.key -out ${name}.crt -sha256 -subj "${SUBJ}/CN=${cn}"
        ;;
    esac
    cd ..
}

Share

comments powered by Disqus