Bash Script to Create an SSL Certificate Key and Request (CSR)

Bash Script to Create an SSL Certificate Key and Request (CSR)

Category : How-to

Get Social!

padlockCreating 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).


28 Comments

Marc

23-Jan-2014 at 12:36 pm

Hi,

thx a lot for this code, you just made my day.

greetz
Marc

    james.coyle

    23-Jan-2014 at 12:54 pm

    I’m glad it helped :)

      subahni

      22-Jan-2020 at 1:20 pm

      HI James,

      I need script for CSR for SAN certificate in IIS server

      pierre

      15-Mar-2022 at 11:43 am

      hi! is there a way to automate the upload of the certificate request and the download of the certificate?

      I am trying to distribute wifi certificates to +100 computers and I am now doing this manually.

      #Generate certificate request profile
      echo ‘[req]
      distinguished_name = req_distinguished_name
      req_extensions = v3_req
      prompt = no
      [req_distinguished_name]
      C = SE
      ST = Stockholm
      L = Danderyd
      O = lala
      OU = MyDivision
      CN = “req_distinguished_name1”
      [v3_req]
      keyUsage = keyEncipherment, dataEncipherment
      extendedKeyUsage = serverAuth
      [alt_names]
      DNS = “req_distinguished_name1”
      ‘ | sudo tee -a /etc/wifi/ssl.cnf
      sudo sed -i -e “s/req_distinguished_name1/$uphostname/g” /etc/wifi/ssl.cnf
      #Generate cetificate request
      sudo openssl req -new -sha256 -key /etc/wifi/user.key -out /etc/wifi/user.csr -config /etc/wifi/ssl.cnf
      clear
      #set Password on key file
      echo “lala” | sudo openssl rsa -des -in /etc/wifi/user.key -passout stdin -out /etc/wifi/user-pwd.key
      #show certificate request to user
      echo “Please send this to IT”
      cat /etc/wifi/user.csr

Peter

28-Jan-2014 at 3:53 pm

Finally someone with an easy workable explanation. Make sure the file has permissions to execute though else you will get a permission denied error.

Would also like to see what to do with certificate bundle once it comes from the ssl registrar.

Thanks

    james.coyle

    28-Jan-2014 at 5:10 pm

    Hi Peter,

    Thank you for the comment.

    The issue with the returned certificate is that it can come in a million different formats, depending on who the CA is. Do you have a specific scenario?

James Andrews

14-Apr-2014 at 9:25 am

I am so glad this was easy to find I was dreading having to write it myself.

I made some modifications. 1) removed all the password stuff since you can generate a csr without a passphrase, and since you can do that you don’t need to remove it afterwards. 2) Added the creation of a self signed certificate file as well, but also added -q option to quiet the echoing of the key, csr, and crt

I have a few other “features” I want to add in later but for now it’s pretty good.

    Forrest Erickson

    9-Sep-2019 at 2:38 pm

    Regarding, ” … Added the creation of a self signed certificate file as well, but also added -q option to quiet the echoing of the key, csr, and crt”

    Share entire bash file please?

sandeep

9-Mar-2015 at 11:18 am

Is there any script for iis 6 to generating CSR private key with out entering in iis 6?

yogesh

4-May-2015 at 11:54 am

Thanks for your explanation.
but how to send this generated CSR to CA and receive the certificate….

It would be great help.

Regards,
Yogesh

sysadmin

26-Aug-2015 at 3:30 pm

Example for generating CSR for multi-domain certificates (UCC):

openssl req -new -newkey rsa:2048 -sha256 -nodes -keyout my.domain.key -out my.domain.req -subj ‘/C=US/ST=Florida/L=Miami/O=Cool IT Company/OU=ITDept/CN=my.domain/[email protected]/subjectAltName=DNS.1=www.my.domain,DNS.2=anothersubdom.my.domain’

    John

    24-Sep-2021 at 3:08 pm

    Thanks!

Declan Veale

8-Sep-2015 at 11:51 am

Fantastic. Thanks for sharing

Jeff Moss

11-Mar-2016 at 3:01 pm

chmod step is missing the “r” off the end.

    james.coyle

    11-Mar-2016 at 3:07 pm

    Post updated – thanks.

Exequiel

2-Jul-2016 at 5:48 am

Excellent!

RAMACHANDRAN U

20-Aug-2016 at 10:14 am

Thanks….. Excellent Help

Andrew

25-Sep-2016 at 1:14 am

if you dont want a password on the key ….
remove the section for removing the key and change key create to …


if [[ $password ]]; then
passopt='-des3'
fi;

#Generate a key
openssl genrsa $passopt -passout pass:$password -out $domain.key 2048 -noout

# because we didnt add a password, we dont need to strip it out.
#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

Andrew

Jeremy

5-Jan-2017 at 9:11 am

Hello James,

I tried modifying your script so I would be able to use it like this:

./gen-cer server.com password

Basically I would like to specify a password straight away and use it for the key/pem file creation and also forward it to the CSR step to skip the pass phrase prompt.

I didn’t succeed so far, but I’m certainly no expert here. Any suggestions on how I could get this to work?

Thanks in advance.

    Martin Fure

    9-Apr-2019 at 9:21 am

    This is probably way too late, but isn’t it possible to just change
    “password=dummypassword”
    to
    “password=$2”
    ?

Chikku

23-Jul-2017 at 8:51 pm

Hi all,
I have a doubt yesterday while running requesting ssl.sh for ordering of new ssl I did aistake according to a script made by my senior we had to first change the year and then run it.
I by mistake ran the script and it generated 2 jks file with previous year and a csr file. Then I realised the mistake, made changes in the year and ran script again and it gave two jks files again with a new car. When I was trying to renew the ssl through URL link it showed that there is no ssl to be renewed,i even removed those two previous ..jks file too. OK ed are suggest me to the way to correct t it. Is it acceptable if we are creating a jks again n again, oR it must be generated only once

Konrad

12-Mar-2018 at 11:54 pm

This script doesn’t resolves wildcard in the cert names. When $domain=*.domain.com
the $domain.csr will be *.domain.com.csr
forgot that? :P

Abdelkarim Mateos Sánchez

9-Jul-2019 at 8:38 am

Very more simple a write certificates.

openssl req -new -newkey rsa:4096 -days 365 -nodes -x509 \
-subj “/C=US/ST=Denial/L=Springfield/O=Dis/CN=www.example.com” \
-keyout http://www.example.com.key -out http://www.example.com.cert

Guilherme Duarte

4-Oct-2019 at 8:24 pm

Thanks ! It save a lot of time.

Gajanan Shinde

8-Apr-2020 at 3:04 pm

Outstanding script !!! Really appreciated !!!

AM

12-Jun-2020 at 2:58 pm

Excellent, thanks a lot. It helped me loading the variables into the openssl cert creation. Cheers!

soumendu

20-Aug-2020 at 3:07 pm

—–
No value provided for Subject Attribute O, skipped
No value provided for Subject Attribute OU, skipped
—————————

Lakshmi Narayana Rao

10-Jan-2023 at 6:01 am

[root@localhost ~]# ls
anaconda-ks.cfg crypto gen-cer
[root@localhost ~]# ./gen-cer test.com
Generating key request for test.com
Extra arguments given.
genrsa: Use -help for summary.
Removing passphrase from key
Can’t open test.com.key for reading, No such file or directory
140335487756096:error:02001002:system library:fopen:No such file or directory:crypto/bio/bss_file.c:69:fopen(‘test.com.key’,’r’)
140335487756096:error:2006D080:BIO routines:BIO_new_file:no such file:crypto/bio/bss_file.c:76:
unable to load Private Key
Creating CSR
Can’t open test.com.key for reading, No such file or directory
140452087740224:error:02001002:system library:fopen:No such file or directory:crypto/bio/bss_file.c:69:fopen(‘test.com.key’,’r’)
140452087740224:error:2006D080:BIO routines:BIO_new_file:no such file:crypto/bio/bss_file.c:76:
unable to load Private Key
—————————
—–Below is your CSR—–
—————————

cat: test.com.csr: No such file or directory

—————————
—–Below is your Key—–
—————————

cat: test.com.key: No such file or directory
[root@localhost ~]#

Leave a Reply to Jeremy Cancel reply

Visit our advertisers

Quick Poll

Do you use ZFS on Linux?

Visit our advertisers