User Tools

Site Tools


howtos:quick_script_to_build_a_ca_and_create_signed_server_certificate

Parameters

Just change the hostname parameter (“HOSTNAME”) to what the server's DNS name is and for how many years the server certificate should be valid for (“CERT_YEARS”).

Default the CA has a valid period of 10 years. If you want to change that just edit the “CA_YEARS” parameter to the expiration period you want.

#!/usr/bin/env bash

SERVER_KEY=server-key.pem
HOSTNAME="myhostname.example.com" #DNS hostname for the server certificate
DAYS_A_YEAR=365

CERT_YEARS=3 #How long should the Server certificate be valid for
CA_YEARS=10 #How long should the CA certificate be valid for

CA_DAYS=$(expr $DAYS_A_YEAR \* $CA_YEARS)
CERT_DAYS=$(expr $DAYS_A_YEAR \* $CERT_YEARS)
echo "# creating a key for our ca"
if [ ! -e ca-key.pem ]; then
    openssl genrsa -out ca-key.pem 4096
fi
echo "# creating a ca"
if [ ! -e ca-cert.pem ]; then
    openssl req -new -x509 -days 3650 -key ca-key.pem -out ca-cert.pem -utf8 -subj "/C=DK/L=Nowhere/O=Red Ocean/CN=my CA"
fi
echo "# create server key"
if [ ! -e $SERVER_KEY ]; then
    openssl genrsa -out $SERVER_KEY 2048
fi
echo "# create a certificate signing request (csr)"
if [ ! -e server-key.csr ]; then
    openssl req -new -key $SERVER_KEY -out server-key.csr -utf8 -subj "/C=DK/L=Nowhere/O=Red Ocean/CN=$HOSTNAME"
fi
echo "# signing our server certificate with this ca"
if [ ! -e server-cert.pem ]; then
    openssl x509 -req -days 1095 -in server-key.csr -CA ca-cert.pem -CAkey ca-key.pem -set_serial 01 -out server-cert.pem
fi

echo "# show the results (no other effect)"
echo "---# Server Key #---"
openssl rsa -noout -text -in $SERVER_KEY
echo "---# CA Key #---"
openssl rsa -noout -text -in ca-key.pem
echo "---# Server CSR #---"
openssl req -noout -text -in server-key.csr
echo "---# Server Cert #---"
openssl x509 -noout -text -in server-cert.pem
echo "---# CA Cert #---"
openssl x509 -noout -text -in ca-cert.pem
howtos/quick_script_to_build_a_ca_and_create_signed_server_certificate.txt · Last modified: d/m/Y H:i by domingo