Welcome!

Java Authors: Roger Strukhoff, Lori MacVittie, Esmeralda Swartz, Trevor Parsons, Sandi Mappic

Related Topics: Java

Java: Article

Using Self-Signed Certificates for Web Service Security

How to compete with trusted certificate authorities

One of the great things about the Java programming language is the Open Source community that provides great applications at little or no cost. An example of this is Apache Tomcat, which provides a solid Web server for development using servlet or JSP technology. Now that Web Service technology is maturing there's a potential for a whole scenario of applications to take advantage of a Swing feature-rich thin client on the front-end coupled to the data verification and business logic already developed in the Web or ejb tier. Such applications are only viable if they can be secure, however, security doesn't have to come at a great cost. The purpose of this article is to demonstrate how Web Service clients can use self-signed security certificates over the secure HTTPS protocol.

The Problem with Using Self-Signed Certificates
HTTPS typically works seamlessly with the non-secure HTTP protocol and doesn't interrupt the user's experience. This is because SSL certificates are designed to be verified and signed by a trusted third party. Verisign is a popular certificate authority. If a Web application requires secure communication, you can pay Verisign to sign your SSL certificate. Once Verisign does that, users on your Web site can switch between HTTP and HTTPS without interruption because all major Web browsers trust certificates signed by Verisign. Verisign is not the only option for getting certificates signed. To save operating costs, or for personal use, you can self-sign your own certificate. However, self-signing your certificate will interrupt your Web site user's experience. Typically the Web browser will display a dialog box asking if you want to trust a certificate you signed.

Web browsers are nice because when they get a certificate signed by an unknown certificate authority there's an option to proceed. When developing Web Service clients for communication over HTTPS it's not so easy. When running Java code there's no dialog box asking about trusting a distrusted certificate authority. The JRE will throw an exception trying to connect over HTTPS to a Web site with a distrusted certificate:

Caused by: sun.security.validator.ValidatorException: No trusted certificate found

There's no way to catch this exception and continue. To get the Web Service to work with a self-signed certificate the JRE has to somehow trust you as a certificate authority.

Solution Outline
To demonstrate a solution to this problem I'll do the following:

  1. Generate and self-sign my own certificate
  2. Configure Tomcat for SSL and make it use that certificate
  3. Create an example Web Service to be called over HTTPS
  4. Generate Web Service client code from WSDL
  5. Demonstrate a client using a custom keystore solution
Generating a Self-Signed Certificate
The JDK comes with a tool, keytool.exe, that is used to mange SSL public/private keys. Keys are added and removed from a binary file on the file system. The default keystore file is JAVA_HOME\jre\lib\security\cacerts. This file contains the list of certificate authorities that the JRE will trust. A list of well-known trusted companies like Verisign is already in the keystore. To see this list, execute with password "changeit":

D:\>keytool -list -rfc -keystore JAVA_HOME\jre\lib\security\cacerts

The keytool application can be used to edit this file. However, just in case something goes wrong it's better to create a new file. If keytool isn't told which file to use it creates HOME/.keystore by default.

To generate your own self-signed certificate execute:

D:\>keytool.exe -genkey -alias Tomcat -keyalg RSA -storepass bigsecret -keypass bigsecret -dname "cn=localhost"

After executing this command there will be a .keystore file in your HOME directory. Here's what the switches mean.

  • genkey: Tells the keytool applica-tion to generate new public/private key pair.
  • alias: The name used to refer to the keys. Remember, the .keystore file can contain many keys.
  • keyalg: Generates public/private keys using the RSA algorithm.
  • storepass: What password is needed to access the .keystore file.
  • keypass: What password is needed to manage the keys.
  • dname: This value is very important. I used "localhost" because this example is designed to run locally. If a Web application is registered as http://www.myserver.com then this value must be www.myserver.com. If the names don't match the certificate will automatically be rejected.
Once the keytool application creates a new public/private key pair it automatically self-signs the key. You have just generated your own self-signed certificate, which can be used for HTTPS communications. You only need to extract the self-signed public key. I'll show how to do this later.

Configuring Tomcat for SSL
Now you have to configure Tomcat to use your self-signed certificate. I used Tomcat 5.0.30. Edit the TOMCAT/conf/server.xml file. Search the file for "8443" and uncomment the <Connector.../> bound to that port. Then you'll have to add the following property to the <Connector.../>:

keystorePass="bigsecret"

When the JRE starts, it will automatically find the HOME/.keystore file and Tomcat will try to access it using the password "bigsecret." When Tomcat starts there should be output to the console that looks similar to:

Feb 4, 2006 3:11:23 PM org.apache.coyote.http11.Http11Protocol start
INFO: Starting Coyote HTTP/1.1 on http-8443

This means the <Connector.../> successfully read the .keystore file and you can now do secure HTTPS connections over the 8443 port. Open a Web browser and try https://localhost:8443/. Because the certificate is self-signed the Web browser will display a dialog box asking about trusting the connection. If accepted, all communications will be secure over HTTPS.

Creating the Web Service
I'm going to use the Apache Axis project to create a very simple Web Service. The Web Service will simulate checking for new e-mail messages. A Web Service client passes a token uniquely identifying a user. The Web Service returns a list of new e-mail messages (see Listing 1).

To get the Web Service deployed, follow these steps:

  1. Cut and paste the code from Listing 1 into a file named Email.jws in Webapp's root directory.
  2. Edit the Web.xml file, adding the Axis servlet and a *.jws mapping (Listing 2).
  3. Put the Axis jar files in WEB-INF/lib. See References at the end of this article for the Axis project URL.
After deploying this article's accompanying WAR file (and configuring Tomcat for SSL), the Web Service is accessible securely over HTTPS at the following URL:

https://localhost:8443/JDJArticleWebService/Email.jws

Using WSDL2Java
The Axis project provides a tool named WSDL2Java that takes a Web Service WSDL and automatically create the Java source code needed to use the Web Service. See Listing 3 for the command line used to generate code for the Email.jws Web Service.

Notice the URL in Listing 3 used to access the WSDL. It's the non-secure HTTP protocol over port 8080. Why not use HTTPS over port 8443? Because of the self-signed certificate, the WSDL2Java tool will encounter the same exact certificate problem this article is trying to provide a solution for. So for now the non-secure protocol must be used. This means the generated code must be altered slightly replacing "http" and "8080" references with "https" and "8443." This article's accompanying client zip file contains the altered code.

Client with a Custom Keystore
The JRE's default keystore is JAVA_HOME\jre\lib\security\cacerts. Java applications will throw an exception whenever they are presented with your self-signed certificate because your certificate isn't in this keystore. Therefore, when developing a client there are two options. The first option is to put your self-signed certificate into the JRE's default keystore. Although this would work it's not a very good solution because customization is required on every client machine. The second option is to generate a custom keystore, put your self-signed certificate into it, and distribute the custom keystore as part of your application (typically inside a jar file).

To create a custom keystore for your client the following has to be done:

  1. Export the self-signed public key from HOME/.keystore.
  2. Import the self-signed public key into a new keystore for you client.
To export the self-signed public key from HOME/.keystore execute the following:

D:\>keytool.exe -export -rfc -alias Tomcat -file Tomcat.cer -storepass bigsecret -keypass bigsecret

Now create the custom keystore for the client by importing Tomcat.cer:

D:>keytool.exe -import -noprompt -trustcacerts -alias Tomcat -file Tomcat.cer -keystore CustomKeystore -storepass littlesecret

Using the switch "-keystore CustomKeystore" will create a new keystore file called "CustomKeystore" in the present working directory. You'll find the CustomKeystore file in the /classpath/resources/keystore directory of this article's client zip file. Replace this one with the file just generated.

Now all that's left to do is to create a client that uses this custom keystore. I'll demonstrate two ways to do this.

The first is to use the Java system properties javax.net.ssl.trustStore and javax.net.ssl.trustStorePassword to point to the CustomKeystore file and provide the password to access it. My example Web Service client in the jdj.wsclient.truststore package takes this approach (see Listing 4). The main() method sets the system properties then creates the objects to use the Web Service. When the JRE needs to access a keystore it looks for the "classpath/resources/keystore/CustomKeystore" file on the file system. Although this is a simple solution it's problematic because the keystore file must be on the file system and the client code must know where to look for it.

The second is a more portable solution that keeps resources inside the jar file and avoids the file system issues. The client code is responsible for reading the CustomKeystore file and somehow using it to create a secure connection to the server. My example Web Service client in the jdj.wsclient.socketfactory package takes this approach (see Listing 5). Listing 5 shows how to read the CustomKeystore file as a resource and use it to create a javax.net.ssl.SSLSocketFactory. Configuring the Axis pluggable architecture, the MySocketFactory class can be then used to create secure Socket objects from this factory.

Conclusion
This article started with a simple problem: I wanted to secure Web Service communications over HTTPS using my own self-signed certificates. By default, the JRE will reject my application's self-signed certificate because I am not a trusted certificate authority. To get secure communications to work I had to get the Web Service client JRE to trust my self-signed certificate. To achieve this, I used the keytool application and generated a new public/private key pair, extracted the self-signed public key, and then created a new keystore and imported this self-signed certificate. I then created a totally self-contained Web Service client that doesn't require any client-side configuration.

References

More Stories By Michael Remijan

Michael J. Remijan is a research programmer at the National Center for Supercomputing Applicaitons (NCSA). His chief responsibilities include data miming and access to terabyte-sized astronomy data sets. Michael received a BS in mathematics and computer science from the University of Illinois and is currently working on an MBA in technology management.

Comments (5)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


@ThingsExpo Stories
The Internet of Things will greatly expand the opportunities for data collection and new business models driven off of that data. In her session at Internet of @ThingsExpo, Esmeralda Swartz, CMO of MetraTech, will discuss how for this to be effective you not only need to have infrastructure and operational models capable of utilizing this new phenomenon, but increasingly service providers will need to convince a skeptical public to participate. Get ready to show them the money! Speaker Bio: Esmeralda Swartz, CMO of MetraTech, has spent 16 years as a marketing, product management, and busin...
Samsung VP Jacopo Lenzi, who headed the company's recent SmartThings acquisition under the auspices of Samsung's Open Innovaction Center (OIC), answered a few questions we had about the deal. This interview was in conjunction with our interview with SmartThings CEO Alex Hawkinson. IoT Journal: SmartThings was developed in an open, standards-agnostic platform, and will now be part of Samsung's Open Innovation Center. Can you elaborate on your commitment to keep the platform open? Jacopo Lenzi: Samsung recognizes that true, accelerated innovation cannot be driven from one source, but requires a...
SYS-CON Events announced today that Red Hat, the world's leading provider of open source solutions, will exhibit at Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Red Hat is the world's leading provider of open source software solutions, using a community-powered approach to reliable and high-performing cloud, Linux, middleware, storage and virtualization technologies. Red Hat also offers award-winning support, training, and consulting services. As the connective hub in a global network of enterprises, partners, a...
P2P RTC will impact the landscape of communications, shifting from traditional telephony style communications models to OTT (Over-The-Top) cloud assisted & PaaS (Platform as a Service) communication services. The P2P shift will impact many areas of our lives, from mobile communication, human interactive web services, RTC and telephony infrastructure, user federation, security and privacy implications, business costs, and scalability. In his session at Internet of @ThingsExpo, Robin Raymond, Chief Architect at Hookflash Inc., will walk through the shifting landscape of traditional telephone a...
SYS-CON Events announced today that Matrix.org has been named “Silver Sponsor” of Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Matrix is an ambitious new open standard for open, distributed, real-time communication over IP. It defines a new approach for interoperable Instant Messaging and VoIP based on pragmatic HTTP APIs and WebRTC, and provides open source reference implementations to showcase and bootstrap the new standard. Our focus is on simplicity, security, and supporting the fullest feature set.
BSQUARE is a global leader of embedded software solutions. We enable smart connected systems at the device level and beyond that millions use every day and provide actionable data solutions for the growing Internet of Things (IoT) market. We empower our world-class customers with our products, services and solutions to achieve innovation and success. For more information, visit www.bsquare.com.
How do APIs and IoT relate? The answer is not as simple as merely adding an API on top of a dumb device, but rather about understanding the architectural patterns for implementing an IoT fabric. There are typically two or three trends: Exposing the device to a management framework Exposing that management framework to a business centric logic • Exposing that business layer and data to end users. This last trend is the IoT stack, which involves a new shift in the separation of what stuff happens, where data lives and where the interface lies. For instance, it’s a mix of architectural style...
From a software development perspective IoT is about programming "things," about connecting them with each other or integrating them with existing applications. In his session at @ThingsExpo, Yakov Fain, co-founder of Farata Systems and SuranceBay, will show you how small IoT-enabled devices from multiple manufacturers can be integrated into the workflow of an enterprise application. This is a practical demo of building a framework and components in HTML/Java/Mobile technologies to serve as a platform that can integrate new devices as they become available on the market.
SYS-CON Events announced today that SOA Software, an API management leader, will exhibit at SYS-CON's 15th International Cloud Expo®, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. SOA Software is a leading provider of API Management and SOA Governance products that equip business to deliver APIs and SOA together to drive their company to meet its business strategy quickly and effectively. SOA Software’s technology helps businesses to accelerate their digital channels with APIs, drive partner adoption, monetize their assets, and achieve a...
SYS-CON Events announced today that Utimaco will exhibit at SYS-CON's 15th International Cloud Expo®, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Utimaco is a leading manufacturer of hardware based security solutions that provide the root of trust to keep cryptographic keys safe, secure critical digital infrastructures and protect high value data assets. Only Utimaco delivers a general-purpose hardware security module (HSM) as a customizable platform to easily integrate into existing software solutions, embed business logic and build s...
Connected devices are changing the way we go about our everyday life, from wearables to driverless cars, to smart grids and entire industries revolutionizing business opportunities through smart objects, capable of two-way communication. But what happens when objects are given an IP-address, and we rely on that connection, sometimes with our lives? How do we secure those vast data infrastructures and safe-keep the privacy of sensitive information? This session will outline how each and every connected device can uphold a core root of trust via a unique cryptographic signature – a “bir...
Internet of @ThingsExpo Silicon Valley announced on Thursday its first 12 all-star speakers and sessions for its upcoming event, which will take place November 4-6, 2014, at the Santa Clara Convention Center in California. @ThingsExpo, the first and largest IoT event in the world, debuted at the Javits Center in New York City in June 10-12, 2014 with over 6,000 delegates attending the conference. Among the first 12 announced world class speakers, IBM will present two highly popular IoT sessions, which will take place November 4-6, 2014 at the Santa Clara Convention Center in Santa Clara, Calif...
Almost everyone sees the potential of Internet of Things but how can businesses truly unlock that potential. The key will be in the ability to discover business insight in the midst of an ocean of Big Data generated from billions of embedded devices via Systems of Discover. Businesses will also need to ensure that they can sustain that insight by leveraging the cloud for global reach, scale and elasticity.
WebRTC defines no default signaling protocol, causing fragmentation between WebRTC silos. SIP and XMPP provide possibilities, but come with considerable complexity and are not designed for use in a web environment. In his session at Internet of @ThingsExpo, Matthew Hodgson, technical co-founder of the Matrix.org, will discuss how Matrix is a new non-profit Open Source Project that defines both a new HTTP-based standard for VoIP & IM signaling and provides reference implementations.

SUNNYVALE, Calif., Oct. 20, 2014 /PRNewswire/ -- Spansion Inc. (NYSE: CODE), a global leader in embedded systems, today added 96 new products to the Spansion® FM4 Family of flexible microcontrollers (MCUs). Based on the ARM® Cortex®-M4F core, the new MCUs boast a 200 MHz operating frequency and support a diverse set of on-chip peripherals for enhanced human machine interfaces (HMIs) and machine-to-machine (M2M) communications. The rich set of periphera...

SYS-CON Events announced today that Aria Systems, the recurring revenue expert, has been named "Bronze Sponsor" of SYS-CON's 15th International Cloud Expo®, which will take place on November 4-6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Aria Systems helps leading businesses connect their customers with the products and services they love. Industry leaders like Pitney Bowes, Experian, AAA NCNU, VMware, HootSuite and many others choose Aria to power their recurring revenue business and deliver exceptional experiences to their customers.
The Internet of Things (IoT) is going to require a new way of thinking and of developing software for speed, security and innovation. This requires IT leaders to balance business as usual while anticipating for the next market and technology trends. Cloud provides the right IT asset portfolio to help today’s IT leaders manage the old and prepare for the new. Today the cloud conversation is evolving from private and public to hybrid. This session will provide use cases and insights to reinforce the value of the network in helping organizations to maximize their company’s cloud experience.
The Internet of Things (IoT) is making everything it touches smarter – smart devices, smart cars and smart cities. And lucky us, we’re just beginning to reap the benefits as we work toward a networked society. However, this technology-driven innovation is impacting more than just individuals. The IoT has an environmental impact as well, which brings us to the theme of this month’s #IoTuesday Twitter chat. The ability to remove inefficiencies through connected objects is driving change throughout every sector, including waste management. BigBelly Solar, located just outside of Boston, is trans...
SYS-CON Events announced today that Matrix.org has been named “Silver Sponsor” of Internet of @ThingsExpo, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Matrix is an ambitious new open standard for open, distributed, real-time communication over IP. It defines a new approach for interoperable Instant Messaging and VoIP based on pragmatic HTTP APIs and WebRTC, and provides open source reference implementations to showcase and bootstrap the new standard. Our focus is on simplicity, security, and supporting the fullest feature set.
Predicted by Gartner to add $1.9 trillion to the global economy by 2020, the Internet of Everything (IoE) is based on the idea that devices, systems and services will connect in simple, transparent ways, enabling seamless interactions among devices across brands and sectors. As this vision unfolds, it is clear that no single company can accomplish the level of interoperability required to support the horizontal aspects of the IoE. The AllSeen Alliance, announced in December 2013, was formed with the goal to advance IoE adoption and innovation in the connected home, healthcare, education, aut...