Last active
September 28, 2021 10:52
-
-
Save renelink/9a4c9efd2ac1b847b4e2c612332deaf0 to your computer and use it in GitHub Desktop.
Create self-signed certificate script
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
usage() { | |
echo "Generates a self-signed certificate." | |
echo | |
echo "Usage: $0 [-h] [-d] [-c <county>] [-s <state>] [-l <city>] [-o] [-n <common_name>] [-f] [<path>]" | |
echo -e "options:" | |
echo -e "\tpath The output path where the key and crt files are generated." | |
echo -e "\t-c The certificate country. E.g. DE or US" | |
echo -e "\t-s The certificate state." | |
echo -e "\t-l The certificate city (location)." | |
echo -e "\t-o The certificate organization." | |
echo -e "\t-n The certificate CN. Default is localhost" | |
echo -e "\t-v Validity in days. Default is 365." | |
echo -e "\t-f Output name. Default is server" | |
echo -e "\t-d Dry run - show command." | |
echo -e "\t-h Print this help." | |
echo | |
exit 1; | |
} | |
dryRun=false | |
subj="" | |
while getopts ":c:s:l:n:o:f:v:dh" o; do | |
case "${o}" in | |
h) | |
usage | |
;; | |
c) | |
subj="${subj}/C=${OPTARG}" | |
;; | |
s) | |
subj="${subj}/ST=${OPTARG}" | |
;; | |
l) | |
subj="${subj}/L=${OPTARG}" | |
;; | |
o) | |
subj="${subj}/O=${OPTARG}" | |
;; | |
n) | |
cn="${OPTARG}" | |
;; | |
v) | |
validDays="${OPTARG}" | |
;; | |
f) | |
outname="${OPTARG}" | |
;; | |
d) | |
dryRun=true | |
;; | |
*) | |
echo "ERROR: Invalid option -$OPTARG" | |
usage | |
;; | |
esac | |
done | |
shift $((OPTIND-1)) | |
subj="${subj}/CN=${cn:-localhost}" | |
outpath="${1:-.}" # current directory if undefined | |
outfilename="${outname:-server}" # server if undefined | |
isCygwin=false | |
case "$(uname -s)" in | |
CYGWIN*|MINGW32*|MSYS*|MINGW*) | |
isCygwin=true | |
;; | |
esac | |
cygwinPatch="" | |
if [ "${isCygwin}" == true ]; then | |
cygwinPatch="export MSYS_NO_PATHCONV=1; "; | |
fi | |
cmd="cd \"${outpath}\"; ${cygwinPatch}openssl req -new -newkey rsa:4096 -days ${validDays:-365} -nodes -x509 -subj \"${subj}\" -keyout \"${outfilename}.key\" -out \"${outfilename}.crt\"" | |
if [ "$dryRun" = true ]; then | |
echo $cmd | |
else | |
bash -c "$cmd" | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just running
will generate a self-signed certificate in the current working directory that is valid for 1 year: