How To Create A Java Keystore Containing A Self Signed Certifate Generated With OpenSSL

A small shell script to generate a private key, a self signed certificate using OpenSSL and finally importing them into a Java keystore. A self signed certificate is usually used during development and test phases, so to make your life easier, the key created is not protected by password. The .p12 file being created by openssl is password protected because lot of users reported that otherwise keytool would refuse to import it. The self signed certificate will expire after 9999 days, I hope it is enough time to complete your development.

# generating private key without password
openssl genrsa -out server.private.key 2048

# generating a certificate signing request
openssl req -new -key server.private.key -out server.csr -subj "/C=IT/ST=Milan/L=Milan/O=MyOffice/OU=IT Department/CN=mywebsite"

# self signing the certificate
openssl x509 -req -days 9999 -in server.csr -signkey server.private.key -out server.crt

# including private key and certificate to a pkcs12, needed to import them into a keystore
openssl pkcs12 -export -in server.crt -inkey server.private.key -out server.p12 -name mywebsite -CAfile ca.crt -caname root -password pass:pazzword

# importing it into a newly created Java keystore
keytool -importkeystore \
        -deststorepass pazzword -destkeypass pazzword -destkeystore keystore \
        -srckeystore server.p12 -srcstoretype PKCS12 -srcstorepass pazzword \
        -alias mywebsite

References

https://devcenter.heroku.com/articles/ssl-certificate-self
http://cunning.sharp.fm/2008/06/importing_private_keys_into_a.html
http://stackoverflow.com/questions/2685512/can-a-java-key-store-import-a-key-pair-generated-by-openssl