Generating Self-signed Certificates for use in Java
There are different ways of creating a self-signed certificate, such as using Java keytool. I prefer openSSL because the keys and certificates generated this way are more standardized and can be used for other purposes. Follow the steps below to generate a self-signed SSL certificate for use when testing SSL applications and servers.
Update If you need to create self signed certificates for use in Java and are running Linux, I have developed a Shell Script you can use. You can find the source and instructions on GitHub.
Update If you need self-signed certificates for Mutual Authentication, please see my follow-up article.
1) Create a host private key using openSSL
openssl genrsa -out HOSTNAME-private.pem 2048
1.1) Derive the public key using openSSL
openssl rsa -in HOSTNAME-private.pem -pubout > HOSTNAME-public.pem
2) Create a self-signed X509 certificate
openssl req -new -x509 -key HOSTNAME-private.pem -out HOSTNAME-certificate.pem -days 365
Country Name (2 letter code) []: US
State or Province Name (full name) []: South Carolina
Locality Name (eg, city) []: Charleston
Organization Name (eg, company) []: Red Hat
Organizational Unit Name (eg, section) []: Consulting
Common Name (eg, YOUR name) []: HOSTNAME
Email Address []:.
3) Create a PKCS12 keystore and import the host certificate
openssl pkcs12 -export -out keystore.pkcs12 -in HOSTNAME-certificate.pem -inkey HOSTNAME-private.pem
4) Convert the PKCS12 keystore to Java keystore using Java keytool
keytool -importkeystore -srckeystore keystore.pkcs12 -srcstoretype PKCS12 -destkeystore keystore.jks -deststoretype JKS
Enter destination keystore password:
Re-enter new password:
Enter source keystore password:
Entry for alias 1 successfully imported.
Import command completed: 1 entries successfully imported, 0 entries failed or cancelled
keystore.jks is the file that you will want to use in your java applications and servers.
References
- http://www.openssl.org/docs/HOWTO/
- http://docs.oracle.com/javase/1.3/docs/tooldocs/win32/keytool.html
Published
03 July 2012