Core Java

Java Keystore Tutorial

 
 
 
 
 
 
 
 
 
 
 

 

1. Introduction

Who of us didn’t visit ebay, amazon to buy anything or his personal bank account to check it. Do you think that those sites are secure enough to put your personal data like (credit card number or bank account number, etc.,)?

Most of those sites use the Socket Layer (SSL) protocol to secure their Internet applications. SSL allows the data from a client, such as a Web browser, to be encrypted prior to transmission so that someone trying to sniff the data is unable to decipher it.

Many Java application servers and Web servers support the use of keystores for SSL configuration. If you’re building secure Java programs, learning to build a keystore is the first step.

2. SSL and how it works

A HTTP-based SSL connection is always initiated by the client using a URL starting with https:// instead of with http://. At the beginning of an SSL session, an SSL handshake is performed. This handshake produces the cryptographic parameters of the session. A simplified overview of how the SSL handshake is processed is shown in the diagram below.

Java KeyStore Tutorial_html_m4e1c1e9d

This is in short how it works:

  1. A browser requests a secure page (usually https://).
  2. The web server sends its public key with its certificate.
  3. The browser checks that the certificate was issued by a trusted party (usually a trusted root CA), that the certificate is still valid and that the certificate is related to the site contacted.
  4. The browser then uses the public key, to encrypt a random symmetric encryption key and sends it to the server with the encrypted URL required as well as other encrypted http data.
  5. The web server decrypts the symmetric encryption key using its private key and uses the symmetric key to decrypt the URL and http data.
  6. The web server sends back the requested html document and http data encrypted with the symmetric key.
  7. The browser decrypts the http data and html document using the symmetric key and displays the information.

The world of SSL has, essentially, three types of certificates: private keys, public keys (also called public certificates or site certificates), and root certificates.

3. Private Keys

The private key contains the identity information of the server, along with a key value. It should keep this key safe and protected by password because it’s used to negotiate the hash during the handshake. It can be used by someone to decrypt the traffic and get your personal information. It like leaving your house key in the door lock.

4. Public Certificates

The public certificate (public key) is the portion that is presented to a client, it likes your personal passport when you show in the Airport. The public certificate, tightly associated to the private key, is created from the private key using a Certificate Signing Request (CSR). After you create a private key, you create a CSR, which is sent to your Certificate Authority (CA). The CA returns a signed certificate, which has information about the server identity and about the CA.

5. Root Certificates

Root CA Certificate is a CA Certificate which is simply a Self-signed Certificate. This certificate represents a entity which issues certificate and is known as Certificate Authority or the CA such as VeriSign, Thawte, etc.

6. Certificate Authorities

Companies who will sign certificates for you such as VeriSign, Thawte, Commodo, GetTrust. Also, many companies and institutions act as their own CA, either by building a complete implementation from scratch, or by using an open source option, such as OpenSSL.

7. Certificate Chain

When a server and client establish an SSL connection, a certificate is presented to the client; the client should determine whether to trust this certificate, a process called the certificate chain. The client examines the issuer of a certificate, searches its list of trusted root certificates, and compares the issuer on the presented certificate to the subjects of the trusted certificates.

If a match is found, the connection proceeds. If not, the Web browsers may pop up a dialog box, warning you that it cannot trust the certificate and offering the option to trust the certificate.

8. Keystore using Java keytool

Java Keytool is a key and certificate management utility. It allows users to manage their own public/private key pairs and certificates. Java Keytool stores the keys and certificates in what is called a keystore. It protects private keys with a password.

Each certificate in a Java keystore is associated with a unique alias. When creating a Java keystore you will first create the .jks file that will initially only contain the private key, then generate a CSR. Then you will import the certificate to the keystore including any root certificates.

9. Keystore Commands

Create Keystore, Keys and Certificate Requests

  • Generate a Java keystore and key pair
    keytool -genkey -alias mydomain -keyalg RSA -keystore keystore.jks -storepass password
  • Generate a certificate signing request (CSR) for an existing Java keystore
    keytool -certreq -alias mydomain -keystore keystore.jks -storepass password -file mydomain.csr
  • Generate a keystore and self-signed certificate
    keytool -genkey -keyalg RSA -alias selfsigned -keystore keystore.jks -storepass password -validity 360

Import Certificates

  • Import a root or intermediate CA certificate to an existing Java keystore
  • keytool -import -trustcacerts -alias root -file Thawte.crt -keystore keystore.jks -storepass password
  • Import a signed primary certificate to an existing Java keystore
    keytool -import -trustcacerts -alias mydomain -file mydomain.crt -keystore keystore.jks -storepass password

Export Certificates

  • Export a certificate from a keystore
    keytool -export -alias mydomain -file mydomain.crt -keystore keystore.jks -storepass password

Check/List/View Certificates

  • Check a stand-alone certificate
    keytool -printcert -v -file mydomain.crt
  • Check which certificates are in a Java keystore
    keytool -list -v -keystore keystore.jks -storepass password
  • Check a particular keystore entry using an alias
    keytool -list -v -keystore keystore.jks -storepass password -alias mydomain

Delete Certificates

  • Delete a certificate from a Java Keytool keystore
    keytool -delete -alias mydomain -keystore keystore.jks -storepass password

Change Passwords

  • Change a Java keystore password
    keytool -storepasswd -new new_storepass -keystore keystore.jks -storepass password
  • Change a private key password
    keytool -keypasswd -alias client -keypass old_password -new new_password -keystore client.jks -storepass password

10. Configure SSL using Keystores and Self Signed Certificates on Apache Tomcat

  1. Generate new keystore and self-signed certificateusing this command, you will prompt to enter specific information such as user name, organization unit, company and location.
    keytool -genkey -alias tomcat -keyalg RSA -keystore /home/ashraf/Desktop/JavaCodeGeek/keystore.jks -validity 360

    Java KeyStore Tutorial_html_m5d3841d

  2. You can list the certificate details you just created using this command
    keytool -list -keystore /home/ashraf/Desktop/JavaCodeGeek/keystore.jks

    Java KeyStore Tutorial_html_131ca506

  3. Download Tomcat 7
  4. Configure Tomcat’s server to support for SSL or https connection. Adding a connector element in Tomcat\conf\server.xml
    <Connector port="8443" maxThreads="150" scheme="https" secure="true" 
    SSLEnabled="true" keystoreFile="/home/ashraf/Desktop/JavaCodeGeek/.keystore" keystorePass="password" clientAuth="false" keyAlias="tomcat" sslProtocol="TLS" />
  5. Start Tomcat and go tohttps://localhost:8443/, you will find the following security issue where the browser will present untrusted error messages. In the case of e-commerce, such error messages result in immediate lack of confidence in the website and organizations risk losing confidence and business from the majority of consumers, that’s normal as your certificate isn’t signed yet by CA such as Thawte or Verisign who will verify the identity of the requester and issue a signed certificate.Java KeyStore Tutorial_html_15195a43
  6. You can click Proceed anyway till you receive you signed certificate.

Ashraf Sarhan

Ashraf Sarhan is a passionate software engineer, an open source enthusiast, has a Bsc. degree in Computer and Information Systems from Alexandria University. He is experienced in building large, scalable and distributed enterprise applications/service in multiple domains. He also has a keen interest in JavaEE, SOA, Agile and Big Data technologies.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

29 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Jiggy
Jiggy
9 years ago

Very interesting article – would it be possible to share an image which explains / shows a mutual authentication? In other words, steps when a server has to validate clients as well.

Thanks in advance.

Ashraf Sarhan
9 years ago
Reply to  Jiggy

Just, take a look on this image which explains the mutual authentication.

http://examples.javacodegeeks.com/wp-content/uploads/2014/08/mutualssl.png

Chandra
Chandra
7 years ago
Reply to  Ashraf Sarhan

Hi Ashraf,
It’s very nice article. I worked with you in pivotal office couple of months ago. I was looking for a smart solution for below. Help will be really appreciated. I need to make a “webservicetemplate” ssl soap service invocation where I have jks file and password with me. Looking for best solution with annotations and spring properties.

marklinux
marklinux
9 years ago

Nice article! I would like to indicate the tool kse (keyStore explorer) at sourceforge. Not affiliate in any way but it sure makes it easier to understand the concepts since the GUI hides the command line, intimidating at first for some.
Nothing wrong with command line , I use myself everyday and should be the preferred way in a production server, but a GUI helps while one is not familiar with the concepts.

Ashraf Sarhan
9 years ago
Reply to  marklinux

Kudos for your addition, It’s a good idea to use the GUI tool specially for beginners.

marklinux
marklinux
9 years ago

Also, I forgot:
Whats up with that spy at the browser window? is some theme, plugin, or something, hummm…, else ? :)

Ashraf Sarhan
9 years ago
Reply to  marklinux

Regarding the spy sign at the top left of the browser window, That’s because I had opened the Chromium in incognito mode.

Ashraf Sarhan
9 years ago

It’s a good point, it adds more security stack. Just, take a look on this image which explains the mutual authentication.

http://examples.javacodegeeks.com/wp-content/uploads/2014/08/mutualssl.png

Prasad
Prasad
9 years ago

Very nice article. Also thanks for sharing the diagram on mutual authentication. I have a question on enryption though. specifically this point:

==
The browser then uses the public key, to encrypt a random symmetric encryption key and sends it to the server with the encrypted URL required as well as other encrypted http data
==

If the URL is also encrypted, how will domain name resolution happen as the DNS server can not decrypt the URL since only the private key can do the same and that is available only with the origin server.

-Prasad

Ashraf Sarhan
9 years ago
Reply to  Prasad

Thanks for raising this point. Although the https guarantees the encrypted secure connection where the whole URL with its data are encrypted, DNS lookup request which resolves the domain name like “javacodegeeks.com” to numbers like “64.64.30.146” is sent through a separate unencrypted traffic before encrypting the URL, leaving you open to spoofing and man-in-the-middle attacks. DNSCrypt can lock that down.

Prasad
Prasad
9 years ago
Reply to  Ashraf Sarhan

Thanks for your response. On DNSCrypt, does it come integrated with browsers or is it an add-on? How can it be plugged in when a user wants to access a secure site?

-Prasad

Ashraf Sarhan
7 years ago
Reply to  Prasad

You will find more information here https://www.opendns.com/about/innovations/dnscrypt

Prasad
Prasad
9 years ago

I also wanted to know which ciphers and hashing are used in the SSL communication.

Ashraf Sarhan
7 years ago
Reply to  Prasad

It was build on the Public-key cryptography (asymmetric) which uses encryption algorithms like RSA and Elliptic Curve Cryptography (ECC) to create the public and private keys. With asymmetric encryption it is computationally easy to generate public and private keys, encrypt messages with the public key, and decrypt messages with the private key. However, it is extremely difficult (or impossible) for anyone to derive the private key based only on the public key.

Banushree
Banushree
9 years ago

for relative urls on an html page [ones of the type “../images/someImage.jpg”], will the browser fetch them on a secure channel? was curious to know how it is accomplished.

Ashraf Sarhan
7 years ago
Reply to  Banushree

Any time an HTML image link is created within a page using the entire, “absolute” URL for the image file’s location, the resulting image link will not be encrypted by any SSL on the site.

For example, the following image link cannot be encrypted by an SSL certificate:

To correct this issue, simply remove your store’s domain from the image tag, creating a relative link:

Ashraf Sarhan
7 years ago
Reply to  Ashraf Sarhan

Sorry, I think the comment doesn’t accept HTML elements! BTW, I mean that you should have the images hosted on your store, then you can use the relative link “/assets/photo1.jpg” instead of “absolute” URL like “http://www.yourvolusionstore.com/assets/photo1.jpg”. Also. if you have an image which hosted on a web server outside your store (e.g. a Flickr account), you’ll need to modify the “absolute” image link to use the secure “https” protocol and the hosting server in question must support the “https” protocol.

gsk
gsk
8 years ago

Hi,
I am created my own keystone using RSA algorithm,
I am encryption and decryption small data is fine, but I try to encrypt long data(my data having a 5725 characters), I am getting “java.lang.ArrayIndexOutOfBoundsException: too much data for RSA block” exception in java. please help me how to solve this problem.

Ashraf Sarhan
7 years ago
Reply to  gsk
chethan sk
chethan sk
8 years ago

Hi Ashraf,
I am trying to create sso login using cas for some of the applications in Tomcat.
I have built cas and have deployed the cas on Tomcat 7.0
Can you please tell me about the configurations to be made for the applications in Tomcat to get SSO Login through cas.

Regards,
Chethan SK

Ashraf Sarhan
7 years ago
Reply to  chethan sk

I don’t have any experience with the CAS tomcat configuration but you can take a look on this https://wiki.jasig.org/display/CASC/Tomcat+Container+Authentication

Zafiah Mohd Yusof
Zafiah Mohd Yusof
8 years ago

Dear Ashraf,

i’ve tried to generate a new jks file but the password that i use recently can’t be identify. How do i check the password that i used before?
TQ.

Ashraf Sarhan
7 years ago

You can check your certificate using “keytool -list -v -keystore keystore.jks” and you will be asked for the password but if you forgot it, you can generate your jks again.

Naresh
Naresh
8 years ago

Excellent explanation.

Ashraf Sarhan
7 years ago
Reply to  Naresh

Thanks

Chinthaka
Chinthaka
7 years ago

Artical was so good.
When I read first tiem I was confuced the phrase “random symmetric encryption key”. Had to read another article to understand what it is. BTW simple understandable article

Amit
Amit
7 years ago

Thanks Ashraf for the nice explanation.

I was trying (enabling the SSL on tomcat) with my local machine and ec2-instance , on local machine it works perfectly fine but when i did it on my ec2-instance and try to access the url with 8443 . i get below error

On chrome :- ERR_SSL_VERSION_OR_CIPHER_MISMATCH
On mozzile :- cannot communicate securely with peer: no common encryption algorithm(s). Error code: SSL_ERROR_NO_CYPHER_OVERLAP .

let me know what is reason behind getting the error on ec2-instance and not locally and how to fix it.

Thanks in advance,
Amit

Ke Pi
7 years ago

There are many kinds of keystores supported by Java. For example, JKS, JCEKS, PKCS12 etc. Here is a great post I find which describes different keystores. http://www.pixelstech.net/article/1408345768-Different-types-of-keystore-in-Java—-Overview

Buddhika
Buddhika
6 years ago

This was very very helpful for me, Highly appreciate the good work..

Back to top button