Skip to content

Instantly share code, notes, and snippets.

@adamrunner
Created March 31, 2016 18:26
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 11 You must be signed in to fork a gist
  • Save adamrunner/285746ca0f22b0f2e10192427e0b703c to your computer and use it in GitHub Desktop.
Save adamrunner/285746ca0f22b0f2e10192427e0b703c to your computer and use it in GitHub Desktop.
bash script to generate a self signed certificate for development use
#!/bin/bash
# Bash shell script for generating self-signed certs. Run this in a folder, as it
# generates a few files. Large portions of this script were taken from the
# following artcile:
#
# http://usrportage.de/archives/919-Batch-generating-SSL-certificates.html
#
# Additional alterations by: Brad Landers
# Date: 2012-01-27
# usage: ./gen_cert.sh example.com
# Script accepts a single argument, the fqdn for the cert
DOMAIN="$1"
if [ -z "$DOMAIN" ]; then
echo "Usage: $(basename $0) <domain>"
exit 11
fi
fail_if_error() {
[ $1 != 0 ] && {
unset PASSPHRASE
exit 10
}
}
# Generate a passphrase
export PASSPHRASE=$(head -c 500 /dev/urandom | tr -dc a-z0-9A-Z | head -c 128; echo)
# Certificate details; replace items in angle brackets with your own info
subj="
C=US
ST=OR
O=Blah
localityName=Portland
commonName=$DOMAIN
organizationalUnitName=Blah Blah
emailAddress=admin@example.com
"
# Generate the server private key
openssl genrsa -des3 -out $DOMAIN.key -passout env:PASSPHRASE 2048
fail_if_error $?
# Generate the CSR
openssl req \
-new \
-batch \
-subj "$(echo -n "$subj" | tr "\n" "/")" \
-key $DOMAIN.key \
-out $DOMAIN.csr \
-passin env:PASSPHRASE
fail_if_error $?
cp $DOMAIN.key $DOMAIN.key.org
fail_if_error $?
# Strip the password so we don't have to type it every time we restart Apache
openssl rsa -in $DOMAIN.key.org -out $DOMAIN.key -passin env:PASSPHRASE
fail_if_error $?
# Generate the cert (good for 10 years)
openssl x509 -req -days 3650 -in $DOMAIN.csr -signkey $DOMAIN.key -out $DOMAIN.crt
fail_if_error $?
@jpylypiw
Copy link

nice script! worked perfectly for me :)

@Geczy
Copy link

Geczy commented Sep 28, 2020

NET::ERR_CERT_COMMON_NAME_INVALID

Doesn't work, must add SAN

@larsfroelich
Copy link

@adamrunner Hey Adam, this is super useful and I would like to include this script in an open-source project, but noticed it does not contain a license. Would you be ok with others using your script with attribution and no other strings attached?

@adamrunner
Copy link
Author

@larsfroelich - sure thing! Thanks for asking, much appreciated.

@larsfroelich
Copy link

@adamrunner thank you! I included it here released under AGPL3 in an open source project called "Hermes", developed by the Associate Professorship of Environmental Sensing and Modeling at the Technical University of Munich (TUM)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment