August 30, 2023

Using Java 17 keytool as Root CA to create Server and User Certificate

Reference

Root CA

Generate Self Signed Root CA

$ keytool -genkeypair -alias RootCA -dname "cn=RootCA, ou=Root_CertificateAuthority, o=CertificateAuthority, c=SE" -validity 3650 -keyalg RSA -keysize 4096 -ext bc:c -keystore RootCA.p12 -storetype PKCS12 -storepass changeit -keypass changeit

Export Root CA certificate and truststore with Root CA

$ keytool -exportcert -alias RootCA -keystore RootCA.p12 -storetype PKCS12 -storepass changeit -rfc -file RootCA.cert.pem

$ keytool -importcert -alias RootCA -trustcacerts -noprompt -keystore truststore.jks -storetype JKS -storepass changeit -keypass changeit -file RootCA.cert.pem 

Server certificate

Generate Server certificate keypair.

$ keytool -genkeypair -alias localhost -dname "cn=localhost, ou=Localhost_Server, o=Server, c=SE" -validity 730 -keyalg RSA -keysize 2048 -keystore localhost.p12 -storetype PKCS12 -storepass changeit -keypass changeit

Generate CSR and sign with Root CA

$ keytool -certreq -alias localhost -keystore localhost.p12 -storetype PKCS12 -storepass changeit | \
    keytool -gencert -alias RootCA -keystore RootCA.p12 -storetype PKCS12 -storepass changeit -ext ku:c=dig,keyEnc -ext "san=dns:localhost,ip:127.0.0.1" -ext eku=serverAuth -rfc > localhost.cert.pem

Create certificate chain

$ cat RootCA.cert.pem >> localhost.cert.pem

Import/replace self signed certificate with Root signed

$ keytool -importcert -alias localhost -trustcacerts -noprompt -keystore localhost.p12 -storetype PKCS12 -storepass changeit -file localhost.cert.pem

Print and verify

$ keytool -list -keystore localhost.p12 -storepass changeit -v

User Certificate

Generate User certificate keypair

$ keytool -genkeypair -alias john -dname "cn=john, ou=John_User, o=User, c=SE" -validity 730 -keyalg RSA -keysize 2048 -keystore john.p12 -storetype PKCS12 -storepass changeit -keypass changeit

Generate CSR and sign with Root CA

$ keytool -certreq -alias john -keystore john.p12 -storetype PKCS12 -storepass changeit | \
    keytool -gencert -alias RootCA -keystore RootCA.p12 -storetype PKCS12 -storepass changeit -ext ku:c=digitalSignature,nonRepudiation,keyEncipherment -ext eku=clientAuth,emailProtection -rfc > john.cert.pem

Create certificate chain

$ cat RootCA.cert.pem >> john.cert.pem

Import/replace self signed certificate with Root signed

$ keytool -importcert -alias john -trustcacerts -noprompt -keystore john.p12 -storetype PKCS12 -storepass changeit -file john.cert.pem

Print and verify

$ keytool -list -keystore john.p12 -storepass changeit -v

No comments: