Java keystore – certificate request and self-sign with openssl

Generate a private key

openssl genrsa -aes256 -out demo.key.pem 2048 

Generate a certificate request
Use the private key to generate a certificate signing request (CSR). The CSR details can be whatever you wish, but they must not exactly match the root CA. For web server certificates, the Common Name must be a fully qualified domain name (eg, www.example.com), whereas for client certificates it can be any unique identifier (eg, an e-mail address). Note that the Common Name cannot be the same as the root certificate.

openssl req -config config/openssl.cnf -key demo.key.pem -new -sha256 -out demo.csr.pem

Sign the certificate

openssl x509 -req -CA ca.cert.pem -CAkey ca.key.pem -in demo.csr.pem -out denoc.cert.pem -days 900 -CAcreateserial

Create a fullchain certificate
The new certificate will only be trusted if the root CA is also trusted. Some applications require the CA certificate to be imported before the new certificate. Others require the CA certificate to be appended to the new certificate.

cat demo.cert.pem config/ca/certs/ca.cert.pem > demo.cert.fullchain.pem

Create a .p12 keystore with openssl.

openssl pkcs12 -export -in demo.cert.fullchain.pem -inkey demo.key.pem -out demo.keystore.p12 -name DEMO

Convert from a .p12 to a java keystore .jks

keytool -importkeystore -srckeystore application.keystore.p12 -srcstoretype PKCS12 -destkeystore application.keystore.jks -alias DEMO

Import the CA certificate in the keystore

keytool -import -alias ROOT -keystore application.keystore.jks -trustcacerts -file ca.cert.pem

Leave a Reply