Created
December 28, 2017 09:36
-
-
Save slavniyteo/bb6597fd238cdbe01750595d3ea9ebd9 to your computer and use it in GitHub Desktop.
Generate x509 key-cert pair signed with CA
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/sh | |
#================== Check dependencies ========================================= | |
if ! which openssl; then | |
echo "Reqiure openssl installed" | |
exit 1 | |
fi | |
#================== Generate CA if need ======================================== | |
CA_PATH="${CA_PATH:-ca}" | |
CA_GENERATE="${CA_GENERATE:-1}" # Comment to avoid generating CA | |
CA_SUBJ="${CA_SUBJ:-/CN=my_trusted_ca}" | |
CA_EXPIRES_AFTER_DAYS="${CA_EXPIRES_AFTER_DAYS:-10958}" | |
if test "${CA_GENERATE}" && test "${CA_GENERATE}" != "0"; then | |
if [ -f "${CA_PATH}.crt" ] || [ -f "${CA_PATH}.key" ]; then | |
echo "CA files are already exists"; | |
exit 2; | |
fi | |
openssl req -x509 \ | |
-newkey rsa:2048 \ | |
-subj "${CA_SUBJ}" \ | |
-keyout "${CA_PATH}.key" \ | |
-out "${CA_PATH}.crt" \ | |
-days "${CA_EXPIRES_AFTER_DAYS}" \ | |
-nodes \ | |
|| exit 3 | |
fi | |
#================== Generate KEY+CRT and sign with CA ========================== | |
CRT_NAME="${CRT_NAME:-out}" | |
CRT_SUBJ="${CRT_SUBJ:-/CN=localhost}" | |
CRT_EXPIRES_AFTER_DAYS="${CRT_EXPIRES_AFTER_DAYS:-10958}" | |
openssl req -newkey rsa:2048 \ | |
-keyout ${CRT_NAME}.key \ | |
-new \ | |
-subj "${CRT_SUBJ}" \ | |
-out "${CRT_NAME}.csr" \ | |
-nodes </dev/null \ | |
&& openssl x509 -req \ | |
-CA "${CA_PATH}.crt" \ | |
-CAkey "${CA_PATH}.key" \ | |
-CAcreateserial \ | |
-in "${CRT_NAME}.csr" \ | |
-out "${CRT_NAME}.crt" \ | |
-days "${CRT_EXPIRES_AFTER_DAYS}" | |
#================== Check result and exit ====================================== | |
EXIT_CODE="$?" | |
if test "$EXIT_CODE" = 0; then | |
echo | |
echo "Success." | |
exit 0 | |
else | |
echo | |
echo "Failed." | |
exit 5 | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment