Skip to content

Instantly share code, notes, and snippets.

@HtwoO
Last active November 14, 2022 02:24
Show Gist options
  • Save HtwoO/9930212d0c70c4688db57cf3b6187a66 to your computer and use it in GitHub Desktop.
Save HtwoO/9930212d0c70c4688db57cf3b6187a66 to your computer and use it in GitHub Desktop.
Self-signed ECDSA Certificate Authority generation script using openssl
#!/usr/bin/env bash
CA_NAME="Swan CA"
ROOT_NAME="Swan Root Cert"
# File path to save to
CA_DIR="self-signed.CA"
CA_KEY_FP="$CA_DIR/swan.key.pem"
CA_CRT_FP="$CA_DIR/swan.crt.pem"
mkdir -p "$CA_DIR"
# use openssl ecparam -list_curves to list available algorithm
# create private key for self-signed root CA
openssl ecparam -genkey -name prime256v1 | \
openssl ec -aes128 -out "$CA_KEY_FP"
# create the certificate file from existing private key
openssl req -x509 -new -sha256 -days 1200 -key "$CA_KEY_FP" \
-subj "/C=CN/O=$CA_NAME/CN=$ROOT_NAME" -out "$CA_CRT_FP"
openssl x509 -noout -text -in "$CA_CRT_FP"
chmod 600 "$CA_KEY_FP"
printf '\nSelf-signed cert %s saved at %s\n' "$CA_NAME" "$CA_CRT_FP"
printf 'Private key for %s saved at %s\n' "$CA_NAME" "$CA_KEY_FP"
#!/usr/bin/env bash
# Required CA cert before generate client cert
CA_DIR="self-signed.CA"
CA_KEY_FP="$CA_DIR/swan.key.pem"
CA_CRT_FP="$CA_DIR/swan.crt.pem"
DOC="Generate ECDSA certificate, you need 'openssl' to run script
Usage:
Generate "$CA_KEY_FP" and "$CA_CRT_FP" first.
Then run script with required username and optional email as argument
"
cmd_example=" $0 vpn.user1 [user1@example.net]"
if [ $# -lt 1 ] || [ $# -gt 2 ]; then
printf '\n%s\n%s\n\n' "$DOC" "$cmd_example"
exit 1
else
if [ $# -eq 1 ]; then
NAME="$1"
EMAIL="$NAME"
fi
if [ $# -eq 2 ]; then
NAME="$1"
EMAIL="$2"
fi
fi
if [ ! -f "$CA_KEY_FP" ] || [ ! -f "$CA_CRT_FP" ]; then
printf 'File %s or %s not present\n' "$CA_KEY_FP" "$CA_CRT_FP"
exit 1
fi
CA_NAME="Swan CA"
# File path to save to
USER_KEY_FP="$CA_DIR/$NAME.key.pem"
USER_CRT_FP="$CA_DIR/$NAME.crt.pem"
USER_CSR_FP="$CA_DIR/$NAME.csr"
printf 'Generate certificate for %s\n\n' "$NAME"
# create private key for user
openssl ecparam -genkey -name prime256v1 | \
openssl ec -aes128 -out "$USER_KEY_FP"
# create the CSR file from existing private key
openssl req -new -sha256 -key "$USER_KEY_FP" -out "$USER_CSR_FP" \
-subj "/C=CN/O=$CA_NAME/CN=$NAME"
#-subj "/C=CN/O=$CA_NAME/CN=$EMAIL"
openssl x509 -addtrust clientAuth -addtrust serverAuth \
-req -days 360 -sha256 -CA "$CA_CRT_FP" -CAkey "$CA_KEY_FP" \
-in "$USER_CSR_FP" -out "$USER_CRT_FP"
openssl x509 -in "$USER_CRT_FP" -noout -text
chmod 600 "$USER_KEY_FP"
printf '\nCertificate for %s saved at %s\n' "$NAME" "$USER_CRT_FP"
printf 'Private key for %s saved at %s\n' "$NAME" "$USER_KEY_FP"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment