Skip to content

Instantly share code, notes, and snippets.

@xcooper
Last active August 4, 2020 06:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save xcooper/1995162f17cf288dc1fa to your computer and use it in GitHub Desktop.
Save xcooper/1995162f17cf288dc1fa to your computer and use it in GitHub Desktop.
Generate private key, certification request, optional PEM files at once
#!/bin/bash
echo "edit this file before you execute it!!"
echo "make sure keytool and openssl commands are in PATH"
echo "Contiune?" | read ANS
echo "give me CN(www.xxx.com.tw)" | read CN
echo "give me default password(length >= 8)" | read -s PASS
set -e
# Edit these arguments
KEYSIZE=2048
# some CA don't support DSA
KEYALG=RSA
# some CA don't want MD5withRSA
SIGALG=SHA256withRSA
# the days that private key will be valid
VALIDITY=3650
# Base name of all files
BN="new_$CN"
byebye() {
echo "Bye!"
exit 0
}
keytool -genkeypair -alias $CN -keyalg $KEYALG -keysize $KEYSIZE -sigalg $SIGALG -validity $VALIDITY -keystore "$BN.jks" -dname "CN=$CN, OU=CWEP, O=GALAXY SOFTWARE SERVICES CORPORATION, L=Taipei, ST=Taiwan, C=TW" -storepass $PASS -keypass $PASS
keytool -list -alias $CN -v -storepass $PASS -keystore "$BN.jks"
echo "is all information of private key OK? press ctrl+c to break or any key to continue."
read ANS
echo "start to create certification request..."
keytool -certreq -keystore "$BN.jks" -file "$BN.csr" -alias $CN -sigalg $SIGALG -keypass $PASS -storepass $PASS
echo "certification request OK!"
echo "should I make additional PEM files? normally, you just answer NO. Answer YES if customer needs your private key in PEM format."
read -p "[NO/yes]?" ANS
if [ $ANS = "NO" ]
then
byebye
fi
echo "convert keystore to PKCS12 format"
keytool -importkeystore -srckeystore $BN.jks -destkeystore "$BN.p12" -deststoretype PKCS12 -srcstorepass $PASS -deststorepass $PASS
echo "convertion finished!"
echo "extract private key with password"
openssl pkcs12 -nocerts -in "$BN.p12" -out "$BN.pem" -password "pass:$PASS" -passin "pass:$PASS" -passout "pass:$PASS"
echo "extract private key OK"
echo "destroy password!"
openssl rsa -in "$BN.pem" -out "$BN.nopass.pem" -passin "pass:$PASS"
echo "OK"
echo "Final report"
echo "---------------------------------------------------------------------------------------------"
echo "$BN.jks - java keystore file having private in it!!!! BACK IT UP!!!"
echo "$BN.csr - certification request file, email it the CA orgnization."
echo "$BN.p12 - openssl keystore with same password, not so important, you can delete it."
echo "$BN.pem - private key file with password"
echo "$BN.nopass.pem - private key file without password, DON'T GIVE IT ANY ONE YOU DON'T TRUST!!!"
echo "---------------------------------------------------------------------------------------------"
byebye
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment