DEV Community

Cover image for How To: generate CSR, Self-signed and CA certificat
Yassine Sellami
Yassine Sellami

Posted on • Edited on

How To: generate CSR, Self-signed and CA certificat

Please make sure you have openssl installed on your machine, or:

Ubuntu: apt-get install openssl
Redhat: yum install -y  openssl
Enter fullscreen mode Exit fullscreen mode

CSR (Certificate Signing Request)

Before you can order an SSL certificate, it is recommended that you generate a CSR from your server.

To avoid the repetition of openssl cli for each domain, The below script allow you to generate CSR and Key with only pass the domain name as an agr:

This script w'll generate two files:

  • .csr : TO be sent to CertProvider for purchase your SSL certificate.
  • .key : Private key used by the server to encrypt and package data for verification by clients.
$ vi csr-key-generator.sh
---
#!/usr/bin/env bash
DOMAIN=$1
if [ -z "$1" ]; then 
    echo "USAGE: $0 domain.com"
    exit
fi

# CSR Attributs, there is a possibility for CertProvider can change information(company, locality..) before issue the certificate.

SUBJ="
C=MA
ST=ST
O=My Company
localityName=City
commonName=$DOMAIN
organizationalUnitName=IT
emailAddress=admin@domain.com
"

# Generate CSR & Private Key
openssl genrsa -out "$DOMAIN.key" 2048
openssl req -new -subj "$(echo -n "$SUBJ" | tr "\n" "/")" -key "$DOMAIN.key" -out "$DOMAIN.csr"

echo "done! enjoy"
Enter fullscreen mode Exit fullscreen mode

Add execution ability to the shell file, and run it:

$ chmod +x csr-key-generator.sh
$ ./csr-key-generator.sh domain.com
output: done! enjoy
$ ls
domain.com.csr domain.com.key
Enter fullscreen mode Exit fullscreen mode

CA (certificate authority)

CA is an entity responsible for issuing digital certificates to verify identities on the internet.

$ openssl req -x509 -sha256 -days 356 -nodes  
    \ -newkey rsa:2048 
    \ -subj "/CN=root.com/C=MA/L=Locality"
    \ -keyout rootCA.key -out rootCA.crt
Enter fullscreen mode Exit fullscreen mode

Self-signed certificate

To-way:

## Use previous CSR,Key: 

$ openssl x509 -req -days 365 -in domain.com.csr 
  \ -signkey domain.com.key -out domain.com.crt

[OR]
## Use previous CA:

$ vi extCert.conf
--- 
subjectAltName = DNS:*.domain.com

$ openssl x509 -req -in domain.com.csr 
  \ -CA rootCA.crt -CAkey rootCA.key -CAcreateserial
  \ -out demo.domain.com.crt -days 365 -sha256 
  \ -extfile extCert.conf
Enter fullscreen mode Exit fullscreen mode

Review the certificate

$ openssl x509 -in domain.com.crt -text -noout
Enter fullscreen mode Exit fullscreen mode

Top comments (0)