Bash Script to Create an SSL Certificate Key and Request (CSR)
Category : How-to
Creating multiple SSL certificates for web servers and application can be a repetitive task. Generally speaking, when creating these things manually you would follow the below steps:
- Create a certificate key.
- Create the certificate signing request (CSR) which contains details such as the domain name and address details.
- Sign the certificate
- Install the certificate and key in the application.
If nothing else, typing out the address and organisation for every certificate can be laborious.
The below script allows you to hard code many of the details to avoid the repetition and only specify the domain name as an argument. The script is dependent on openssl which can be installed using your distributions package manger or from their website. Use apt-get on Debian/ Ubuntu:
apt-get install openssl
Once you have openssl installed, copy the below script to a file called gen-cer.
vi gen-cer
#!/bin/bash #Required domain=$1 commonname=$domain #Change to your company details country=GB state=Nottingham locality=Nottinghamshire organization=Jamescoyle.net organizationalunit=IT [email protected] #Optional password=dummypassword if [ -z "$domain" ] then echo "Argument not present." echo "Useage $0 [common name]" exit 99 fi echo "Generating key request for $domain" #Generate a key openssl genrsa -des3 -passout pass:$password -out $domain.key 2048 -noout #Remove passphrase from the key. Comment the line out to keep the passphrase echo "Removing passphrase from key" openssl rsa -in $domain.key -passin pass:$password -out $domain.key #Create the request echo "Creating CSR" openssl req -new -key $domain.key -out $domain.csr -passin pass:$password \ -subj "/C=$country/ST=$state/L=$locality/O=$organization/OU=$organizationalunit/CN=$commonname/emailAddress=$email" echo "---------------------------" echo "-----Below is your CSR-----" echo "---------------------------" echo cat $domain.csr echo echo "---------------------------" echo "-----Below is your Key-----" echo "---------------------------" echo cat $domain.key
Make sure your script has execute permissions.
chmod +x gen-cer
You can then call the script with ./gen-cer and specify your domain name as an argument. For example:
./gen-cer mynewwebserver.jamescoyle.net
The script will then output the key as well as the CSR which you will need to submit to your certificate authority (CA).