Last active
May 19, 2016 12:16
-
-
Save mruzicka/4129d99fce6be311f436676e9bc4b787 to your computer and use it in GitHub Desktop.
Script to create X.509 certificates using openssl
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/bash | |
TARGETDIR="${1}" | |
CA_KEY="${TARGETDIR}/cakey.pem" | |
CA_CRT="${TARGETDIR}/cacert.pem" | |
SERVER_KEY="${TARGETDIR}/server.key" | |
SERVER_CSR="${TARGETDIR}/server.csr" | |
SERVER_CRT="${TARGETDIR}/server.crt" | |
KEY_LENGTH=1024 | |
DAYS_VALID=10 | |
output_request_config() { | |
if [ $# -gt 0 ]; then | |
CN="${1}" | |
else | |
CN="Ruby Test CA/emailAddress=security@ruby-lang.org" | |
fi | |
echo "[ req ]" | |
echo "default_md = sha1" | |
echo "utf8 = yes" | |
echo "string_mask = utf8only" | |
echo "distinguished_name = distinguished_name" | |
echo "prompt = no" | |
echo | |
echo "[ distinguished_name ]" | |
echo "C = JP" | |
echo "ST = Shimane" | |
echo "L = Matz-e city" | |
echo "O = Ruby Core Team" | |
echo "CN = $CN" | |
} | |
output_request_extensions() { | |
NAME="${1}" | |
if [ $# -gt 1 ] && [ "${2}" -gt 0 ]; then | |
CA="TRUE" | |
else | |
CA="FALSE" | |
fi | |
echo "[ ${NAME} ]" | |
echo "basicConstraints = CA:${CA}" | |
echo "nsComment = OpenSSL Generated Certificate" | |
echo "subjectKeyIdentifier = hash" | |
echo "authorityKeyIdentifier = keyid, issuer" | |
} | |
# Generate a private key for the CA's root certificate | |
openssl genrsa -out "${CA_KEY}" "${KEY_LENGTH}" | |
# Generate the CA's root (self signed) certificate | |
{ | |
output_request_config | |
output_request_extensions "ca_ext" 1 | |
} | { | |
openssl req \ | |
-new -x509 -config /dev/stdin -extensions "ca_ext" \ | |
-set_serial "${RANDOM}" -days "${DAYS_VALID}" \ | |
-key "${CA_KEY}" \ | |
-out "${CA_CRT}" | |
} | |
# Generate a private key for the servers certificate (and certificate request) | |
openssl genrsa -out "${SERVER_KEY}" "${KEY_LENGTH}" | |
# Generate a certificate request for the server certificate | |
{ | |
output_request_config "localhost" | |
} | { | |
openssl req \ | |
-new -config /dev/stdin \ | |
-key "${SERVER_KEY}" \ | |
-out "${SERVER_CSR}" | |
} | |
# Sign the server certificate request into a certificate | |
{ | |
output_request_extensions "crt_ext" | |
} | { | |
openssl x509 \ | |
-req -CA "${CA_CRT}" -CAkey "${CA_KEY}" \ | |
-extfile /dev/stdin -extensions "crt_ext" \ | |
-set_serial "${RANDOM}" -days "${DAYS_VALID}" \ | |
-in "${SERVER_CSR}" \ | |
-out "${SERVER_CRT}" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment