Last active
February 11, 2024 01:25
-
-
Save atheiman/e99bc67fdf2444df9b1240abd446be27 to your computer and use it in GitHub Desktop.
Generate a CA cert and private key, then issue a cert to a server
This file contains 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/sh | |
set -eux | |
CA_FILE_PREFIX="${CA_FILE_PREFIX:-"example-corp-ca"}" | |
CA_CN="${CA_CN:-"Example Corp CA"}" | |
CA_SUBJ="${CA_SUBJ:-"/C=US/O=Example Corp/CN=${CA_CN}"}" | |
SERVER_CN="${SERVER_CN:-"server.example.com"}" | |
SERVER_FILE_PREFIX="${SERVER_FILE_PREFIX:-"${SERVER_CN}"}" | |
SERVER_SUBJ="${SERVER_SUBJ:-"/C=US/O=Example Corp/CN=${SERVER_CN}"}" | |
CA_KEY_FILE="${CA_KEY_FILE:-"${CA_FILE_PREFIX}.key"}" | |
CA_CERT_FILE="${CA_CERT_FILE:-"${CA_FILE_PREFIX}.crt"}" | |
CA_CERT_VALID_DAYS="${CA_CERT_VALID_DAYS:-"10000"}" | |
SERVER_CSR_FILE="${SERVER_CSR_FILE:-"${SERVER_FILE_PREFIX}.csr"}" | |
SERVER_KEY_FILE="${SERVER_KEY_FILE:-"${SERVER_FILE_PREFIX}.key"}" | |
SERVER_CERT_FILE="${SERVER_CERT_FILE:-"${SERVER_FILE_PREFIX}.crt"}" | |
SERVER_CERT_VALID_DAYS="${SERVER_CERT_VALID_DAYS:-"1000"}" | |
# Generate root CA private key and cert if the files do not already exist | |
if [ ! -f "${CA_KEY_FILE}" ] && [ ! -f "${CA_CERT_FILE}" ]; then | |
openssl req \ | |
-x509 \ | |
-sha256 \ | |
-nodes \ | |
-days "${CA_CERT_VALID_DAYS}" \ | |
-newkey rsa:2048 \ | |
-keyout "${CA_KEY_FILE}" \ | |
-out "${CA_CERT_FILE}" \ | |
-subj "${CA_SUBJ}" | |
fi | |
# Inspect the generated CA cert | |
openssl x509 -text -noout -in "${CA_CERT_FILE}" | |
# Create server CSR and private key | |
openssl req \ | |
-out "${SERVER_CSR_FILE}" \ | |
-new \ | |
-newkey rsa:2048 \ | |
-nodes \ | |
-keyout "${SERVER_KEY_FILE}" \ | |
-subj "${SERVER_SUBJ}" | |
# Inspect the generated CSR | |
openssl req -text -noout -verify -in "${SERVER_CSR_FILE}" | |
# Sign server cert with root CA private key and cert | |
openssl x509 \ | |
-req \ | |
-in "${SERVER_CSR_FILE}" \ | |
-CA "${CA_CERT_FILE}" \ | |
-CAkey "${CA_KEY_FILE}" \ | |
-CAcreateserial \ | |
-out "${SERVER_CERT_FILE}" \ | |
-days "${SERVER_CERT_VALID_DAYS}" \ | |
-sha256 | |
# Inspect the generated server cert | |
openssl x509 -text -noout -in "${SERVER_CERT_FILE}" | |
# Verify CA cert signed server cert | |
openssl verify -verbose -CAfile "${CA_CERT_FILE}" "${SERVER_CERT_FILE}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment