How to properly generate a .csr file

During my short IT-career, I have dealt with alot people who struggle with generating a .csr file (certificate signing request) on Linux. Windows (especially IIS) have a more clearer approach so that can most of the people figure out by themselves without having to ask to many questions :)

The following example generates a .csr and a .key file for the Company “Company Name”, located in some country in the city “City”. Just replace the variables to your liking.

DOMAIN=www.example.com
COUNTRY=2 letter country code
ORG="Company Name"
CITY="City"
STATE="State"
EMAIL="youremail@example.com"

openssl req -utf8 -nameopt multiline,utf8 -new -newkey rsa:2048 -nodes -sha256 -out $DOMAIN.csr -keyout $DOMAIN.key -subj "/C=${COUNTRY}/ST=${STATE}/L=${CITY}/O=${ORG}/OU=IT/CN=$DOMAIN/emailAddress=${EMAIL}"

Sometimes, you do want to generare a .csr file that includes two or more domains – a SAN certificate. Using the same variable as above, we can now add more CN's to the .csr:

openssl req -utf8 -nameopt multiline,utf8 -new -newkey rsa:2048 -nodes -sha256 -out $DOMAIN.csr -keyout $DOMAIN.key -subj "/C=${COUNTRY}/ST=${STATE}/L=${CITY}/O=${ORG}/OU=IT/CN=$DOMAIN/emailAddress=webmaster@example.com" -config <(
cat <<-EOF
[req]
default_bits = 2048
default_md = sha256
req_extensions = req_ext
distinguished_name = dn
[ dn ]
[ req_ext ]
subjectAltName = @alt_names
[alt_names]
DNS.1 = www.example.se
DNS.2 = example.se
DNS.3 = www.example.it
DNS.3 = example.it
DNS.3 = www.example.fi
DNS.3 = example.fi
DNS.3 = www.example.org
DNS.3 = example.org
EOF
)

Lets simplify this even more, with a script!

Running this script, will prompt you with a small dialog that ask you for the domain-name you want a .csr file for. It creates the .key and .csr, and prints out the .csr in the termina

#!/bin/bash
echo -n "Please enter the full Common Name (CN)"
read DOMAIN

COUNTRY=SE
ORG="Company"
CITY="City"
STATE="State"
EMAIL="admin@domain.tld"

openssl req -utf8 -nameopt multiline,utf8 -new -newkey rsa:2048 -nodes -sha256 -out $DOMAIN.csr -keyout $DOMAIN.key -subj "/C=${COUNTRY}/ST=${STATE}/L=${CITY}/O=${ORG}/OU=IT/CN=$DOMAIN/emailAddress=$EMAIL" -config <(
cat <<-EOF
[req]
default_bits = 2048
default_md = sha256
req_extensions = req_ext
distinguished_name = dn
[ dn ]
[ req_ext ]
subjectAltName = @alt_names
[alt_names]
DNS.1 = $DOMAIN
EOF
)

echo "private key and certificate request created"
cat $DOMAIN.csr
exit 0 

I hope this can prevent some headache for one or two :)

#linux #openssl #csr #ssl #tls #certificate