Ashraf Sarhan

About 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.

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.

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 two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

12 Responses to "Java Keystore Tutorial"

  1. Jiggy says:

    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.

  2. marklinux says:

    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.

  3. marklinux says:

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

  4. 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

  5. Prasad says:

    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

    • 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 says:

        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

  6. Prasad says:

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

  7. Banushree says:

    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.

Leave a Reply


4 − one =



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

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

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close