Thursday, September 18, 2008

Create Long-Lasting Self-signed Certificate, Private Key, and Certificate Signing Request with a Bash Script (genkeycsrcrt.sh) and Openssl

The following bash script generates a long-lasting self-signed certificate, private key, and certificate signing request. It uses openssl which is included in most unix-based operating systems like OS X and Linux. This is really helpful for anything that requires SSL (HTTPS, etc.).

Enter changeit for all pass phrase prompts (no matter what). Just hit (return) at the challenge password prompt. You must be sure that that common name you enter is your fully-qualified hostname (example: hostname.domain.com) that people will be using to get to your server(s). It will output a .csr, .crt, and .key file (for example: hostname.domain.com.csr, hostname.domain.com.crt, and hostname.domain.com.key), but the only two you'll probably need in this case are the .crt and .key files.

genkeycsrcrt.sh

#!/bin/bash

# genkeycsrcrt.sh
# Written by Gary S. Weaver 2008-09-18
# This creates long-lasting self-signed certificate, private key, and certificate request.
# It requires openssl.

set -e

host=$1

if [ ! -n "$host" ]
then
  echo "usage: genkeycsrcrt.sh hostname.domain.com"
  exit
fi

openssl genrsa -des3 -out "$host.key" 4096
openssl req -new -key "$host.key" -out "$host.csr"
openssl x509 -req -days 99999 -in "$host.csr" -signkey "$host.key" -out "$host.crt"
openssl rsa -in "$host.key" -out "$host.key.insecure"
mv "$host.key" "$host.key.secure"
mv "$host.key.insecure" "$host.key"
rm "$host.key.secure"
Here's one written by Drew Stinnett:
#!/bin/sh

if [ ! $1 ]; then
 echo "Need cn" 2>&1
 exit 1
fi

TMPDIR=$(mktemp -d)
cd $TMPDIR
openssl genrsa -out $1.key 2048
openssl req -new -x509 -nodes -days 7300 -key $1.key -out $1.crt

echo "Keys created in $TMPDIR"

No comments: