Home » Java » Core Java » Java Security Tutorial – Step by Step guide to create SSL connection and certificates

About Mainak Goswami

Mainak Goswami
Mainak Goswami is an experienced Technology Consultant specializing in JEE, Web Development and Open source technologies. He is currently based out of United Kingdom. He is a technology enthusiast trying to explore the latest in the world of technology. His current area of interest is Mobility, NoSQL and Cloud computing. In past time he loves blogging on his website Idiotechie.

Java Security Tutorial – Step by Step guide to create SSL connection and certificates

Step_by_StepIn our series of articles on applying JEE security we present you another detailed tutorial on how to create a SSL connection and create certificates in a Java EE application. As mentioned in our previous article Secured Socket Layer (SSL)/ Transport Layer Security (TLS) will enable a secured connection between the client and the web server. The client will use HTTPS connection to use the web resources. Java provides various security based APIs which can help to create a secured connection with the client and sending / receiving messages in an encrypted format:

  • Java Cryptography Architecture(JCA)
  • Java Cryptographic Extension(JCE)
  • Java Secured Socket Extension (JSSE)

To enable a SSL connection the web server needs to have a Digital Certificate which will allow clients to trust the authenticity of the web application. The application which wants to send an encrypted message applies for a Digital Certificate from the Certificate Authority (CA). The CA validates the application owner details and other identification details and issues a digital certificate.
In Public Key Infrastructure (PKI) scheme a digital certificate is issued by a CA and it contains Distinguished Name(DN) /owner’s name/ subject, a serial number to uniquely identify the certificate, owner’s public key, issuing date, expiry date, Distinguished name of the CA, digital signature of the issuing authority (CA), signature algorithm which is used to create the signature. Digital certificates issued by the CA can be kept in registries so that the authenticating users can use the owner’s public key.

How does browsers recognizes the authenticity of the application or website using the certificates?

All commercial CA have relationship with the major web browsers so that their root certificates are embedded in their browsers. The browser’s SSL compatibility can be checked through the certificate store which provides the information about the CA certificates which are stored in the browser’s store. Alternatively the CA websites also provide the information about the browser’s SSL compatibility.

The below image shows the certificate details for a sample website http://abcgen.uk. The below certificate assures the client that the authenticity of the owner has been verified and digital certificate has been issued to ABCGen Idiotechie plc with a Common Name as www.abcgen.uk.

Note: For security reasons we have not used any reference to a live website. The example used in this article is for illustrative and learning purposes only. This example shows that the certificate is issued by Verisign as Class 3 which denotes that Verisign has performed an independent verification and validation of the owner. This is not a specified PKI standard. The next field denotes the validity of this certificates. The fingerprints denotes the public key but in an encoded format. The data is hashed using a cryptographic hash function SHA1 and MD5.

Sample Certificate Details

The below diagram displays the Certificate Hierarchy. The first item denotes the Root certificate and the second one displays the extended validation. The certificate authorities (CA) provide higher security certificates known as Extended validation. All the major web browser’s key store will contain the information about the root and extended validation which will enable them to authenticate a particular application’s authenticity.

Certificate Hierarchy

Hope everybody got the concept. Now let’s try some coding.

Products used:

  • IDE: Netbeans 7.2
  • Java Development Kit (JDK): Version 6
  • Glassfish server: 3.1
  • Authentication Mechanism: Form Based authentication
  • Authentication server: LDAP OpenDS v2.2


Create a SSL connection between web server and the client.

Step 1:

Create a Server certificate in Glassfish server
Open a command prompt in windows -> Go to the {domain_dir}/config directory where {domain_dir} denotes the Glassfish domain path.
e.g. C:\NetBeans\7.2\config\GF3\domain1\config>

Step 2:

We will use keytool command to generate the certificates. Keytool is a key and certificate management utility provided by Java SE 6.
Run the keytool command as follows:

>keytool -genkey -alias server-alias -keyalg RSA -keypass changeit -storepass changeit -ke
ystore keystore.jks
The command will ask for the following details:
What is your first and last name?
[Unknown]:  localhost  <<For testing purposes we need to use localhost since it maps to the application server hostname. Ideally in production environments this field should include application server’s name.>>
What is the name of your organizational unit?
[Unknown]:  idiotechie
What is the name of your organization?
[Unknown]:  idiotechie
What is the name of your City or Locality?
[Unknown]:  edinburgh
What is the name of your State or Province?
[Unknown]:  EDN
What is the two-letter country code for this unit?
[Unknown]:  GB
Is CN=localhost, OU=idiotechie, O=idiotechie, L=edinburgh, ST=EDN, C=GB correct?
[no]:  YES

Step 3:

Export the generated certificate to server.cer file.

>keytool -export -alias server-alias -storepass changeit -file server.cer -keystore keysto
Certificate stored in file <server.cer>

Step 4:

Add the certificate to the trust store file

>keytool -import -v -trustcacerts -alias server-alias -file server.cer -keystore cacerts.j
ks -keypass changeit -storepass changeit
Owner: CN=localhost, OU=idiotechie, O=idiotechie, L=edinburgh, ST=EDN, C=GB
Issuer: CN=localhost, OU=idiotechie, O=idiotechie, L=edinburgh, ST=EDN, C=GB
Serial number: 519e7165
Valid from: Thu May 23 20:43:33 BST 2013 until: Wed Aug 21 20:43:33 BST 2013
Certificate fingerprints:
MD5:  34:B7:71:CD:C9:56:9A:EA:0C:F2:91:50:EA:7F:4B:64
SHA1: AA:DE:EC:1B:27:8E:BC:3A:7A:82:8C:B7:FA:C3:AA:11:2F:97:1F:2C
Signature algorithm name: SHA1withRSA
Version: 3
Trust this certificate? [no]:  YES
Certificate was added to keystore
[Storing cacerts.jks]

Step 5:

  Verify if the certificate was successfully added into the keystore.

>keytool -list -v -keystore keystore.jks
Enter keystore password:
Alias name: server-alias
Creation date: 23-May-2013
Entry type: PrivateKeyEntry
Certificate chain length: 1
Owner: CN=localhost, OU=idiotechie, O=idiotechie, L=edinburgh, ST=EDN, C=GB
Issuer: CN=localhost, OU=idiotechie, O=idiotechie, L=edinburgh, ST=EDN, C=GB
Serial number: 519e7165
Valid from: Thu May 23 20:43:33 BST 2013 until: Wed Aug 21 20:43:33 BST 2013
Certificate fingerprints:
MD5:  34:B7:71:CD:C9:56:9A:EA:0C:F2:91:50:EA:7F:4B:64
SHA1: AA:DE:EC:1B:27:8E:BC:3A:7A:82:8C:B7:FA:C3:AA:11:2F:97:1F:2C
Signature algorithm name: SHA1withRSA
Version: 3

Step 6:

Validate if the certificate was successfully added into the trust store.

>keytool -list -keystore cacerts.jks
Enter keystore password:

server-alias, 23-May-2013, trustedCertEntry,
Certificate fingerprint (MD5): 34:B7:71:CD:C9:56:9A:EA:0C:F2:91:50:EA:7F:4B:64

So now the certificate is available both in the keystore and truststore. The keystore contains the private key of the server while truststore contains the CA certificates or the public keys only. This is a cleaner demarcation of the certificates and the keys where private keys can be kept in more secured environment in the keystores but public keys can be kept in more accessible option in the truststore.
However in this example since we do not have a CA certificate the server certificate is stored in the trusted store.

Step 7:

From the server configuration perspective let’s go to the server admin console.
Then click Configurations -> server-config->HTTP Service ->http-listeners-2.
Http-Listeners-2 denotes the secured HTTPS port 8181.
Click the SSL tab and modify the Certificate Nick-name to “server-alias” as per the certificate we have created above.

Application Server SSL settings

Step 8:

Restart the server.

So all the server related configurations are now done.

Let’s move into the application code.
We will use the same application code used for http://idiotechie.com/secure-web-application-in-java-ee6-using-ldap/.

The only change required is in web.xml where the transport-guarantee will be changed from none to confidential.


The CONFIDENTIAL protection mode is used when the application wants to prevent others entities to view the contents of the transmission.

Build, deploy and run the application.

Now even if you try to type the URL http://localhost:9999/SampleWebApp/index.jsp the server will redirect the users to the secured HTTPS connection through https://localhost:8181/SampleWebApp/index.jsp. Since the certificate produced by the server is self signed one instead of a certificate from CA the browsers gives a warning message notifying that the website’s security certificate cannot be trusted. This is due to the fact that browser’s truststore does not contain these certificates.

Secured Application

We can add the certificate in browser’s exception list to avoid future warnings. Let’s now try to check the certificate details of the sample application from the Mozilla Firefox browser:

Localhost Certificate Details

Hope my readers were able to understand how to create digital certificate and secure a web application. If you like this article please share this in the social networking sites and help us grow.

 Download Sample Code below:


Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!


1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design


and many more ....


Receive Java & Developer job alerts in your Area


Leave a Reply

6 Comments on "Java Security Tutorial – Step by Step guide to create SSL connection and certificates"

Notify of
Sort by:   newest | oldest | most voted
Mario Guerrero

Thanks Mainak Goswami,

Great post.

pooja mittal

Great.If you are thinking to learn java online then i want to suggest you a place where you can join free online java course. It is totally free. The course is spread over 128 lectures in 21 sections with practice problems in sections intended to enhance your practical knowledge of concepts learnt throughout the section.



It’s not free its asking for 99$ is there any other way to learn it in free..?

I have create a certificate using keytool and java 6. But certificate doesn’t support for java 7. Does java version matters while creating certificate. My server is running on java 7 and client is using java 6. I have import certificate in are path. But still it doesn’t work. It through error as : javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated at sun.security.ssl.SSLSessionImpl.getPeerCertificates(Unknown Source) at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:128) at org.apache.http.conn.ssl.SSLSocketFactory.connectSocket(SSLSocketFactory.java:339) at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:123) at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:147) at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:101) at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:381) at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:641) at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:576) at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:554) at com.geo.ml.HttpClientImpl.download(HttpClientImpl.java:118) at com.geo.ml.HttpClientImpl.download(HttpClientImpl.java:369) at com.geo.ml.main.HttpMain.main(HttpMain.java:47) Thanks Prashant

Is there any way I can have a video tutorial on SSL connection and certificates


best details about this topic as compare to other’s