---
title: Function for bash or zsh to generate SSL requests and certificates
author: james
type: post
date: 2015-07-03T14:19:10+00:00
url: /2015/07/function-for-bash-or-zsh-to-generate-ssl-requests/
categories:
  - Uncategorized

---
Rather than memorising annoying OpenSSL options, stick this in your profile, edit the &#8216;SUBJ&#8217; bit, and you&#8217;ll be generating keys with ease.

<pre class="lang:zsh decode:true " title="SSL certificate generator" ># 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="&lt;&lt;&lt; SET THIS BIT &gt;&gt;&gt;"

    if [ -z "$cn" -o "$cn" = "-h" ]; then
        echo "usage: $0 &lt;common name&gt; [csr|crt]" &gt;&2
        echo "  csr - generate a certificate signing request (default)" &gt;&2
        echo "  crt - generate a self-signed certificate" &gt;&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" &gt;&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 ..
}
</pre>