Skip to content

Instantly share code, notes, and snippets.

@mariogasparoni
Last active March 23, 2022 15:53
Show Gist options
  • Save mariogasparoni/a6b9d431977ec1f510c0d32264686c1c to your computer and use it in GitHub Desktop.
Save mariogasparoni/a6b9d431977ec1f510c0d32264686c1c to your computer and use it in GitHub Desktop.
Generate a private key (.key file) a certificate (.crt file) and a .pem file (containing the private key and a certificate)
#!/bin/bash
# Generate a private key (.key file) a certificate (.crt file) and
# a .pem file (containing the private key and a certificate)
# author: mariogasparoni.
# Usage: ./generate-pem-certificate-and-key.sh <HOSTNAME|IP-ADDRESS>
set -e
HOSTNAME=$1
if [ -z "$HOSTNAME" ]
then
echo "Usage: ./generate-pem-certificate-and-key.sh <HOSTNAME|IP-ADDRESS>"
exit 1;
fi
CERTNAME=$HOSTNAME
sudo apt-get install -y gnutls-bin
#Generate private key
certtool --generate-privkey --outfile $CERTNAME.key
echo 'organization = '$HOSTNAME > /tmp/certtool.tmpl
echo 'cn = '$HOSTNAME >> /tmp/certtool.tmpl
echo 'unit = '$HOSTNAME >> /tmp/certtool.tmpl
echo 'dns_name = '$HOSTNAME >> /tmp/certtool.tmpl
# Bypass Java Exception: "javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No subject alternative names present"
if [[ $HOSTNAME =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]
then
echo 'ip_address = '$HOSTNAME >> /tmp/certtool.tmpl
fi
#Generate certificate using private key
certtool --generate-self-signed --load-privkey $CERTNAME.key --template /tmp/certtool.tmpl > $CERTNAME.crt
#Generate PEM's container, using both private key and certificate
cat $CERTNAME.key $CERTNAME.crt > $CERTNAME.pem
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment