Posts Tagged ‘Security’

How to develop a standalone SSL web service

12/08/2010 14 comments

How to develop a standalone SSL web service

Hi! Today, I´m gonna show you how to develop a simple SSL web service. Please note that this is not a “enterprise” way of developing a secure web service, but this may be very useful for testing purposes.


To develop this service, you need to use a Sun/Oracle JVM (I tested with 1.6 VM, but should work with 1.5, too). This is not gonna work in any other kind of VM. Also, you need to have JAX-WS in your classpath.

The code

The code begins with the development of the web service itself. I used a standard JAX-WS service as an example, so my service looks like this:

public class SOAPService {

	public String test() {
		return "Hello, SSL world!";

Next, we may use Java´s Endpoint class to create our object as an web service. The code is like

Endpoint endpoint = Endpoint.create(new SOAPService());

At this point, you need to create the server, and to create the server, you need a .jks (Java Keystore) file. You may create this file using JDK´s (or JRE´s) tooling, but I prefer using a GUI to do so. Personally, I like Lazgo´s KeyStore Explorer (available here). I won´t get in details here on how to create the JKS file; if you don´t know how to do it, you may want to have a look here.

Note: be aware that the CN attribute of your certificate must be equal to your host´s name!

After creating the JKS file, we are ready to create our HTTPS server. I won´t explain this code very much, as it should be pretty self-explanatory:

public static void main(String[] args) throws Exception {
		Endpoint endpoint = Endpoint.create(new SOAPService());
		SSLContext ssl =  SSLContext.getInstance("SSLv3");
		KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); 
		KeyStore store = KeyStore.getInstance(KeyStore.getDefaultType());

		//Load the JKS file (located, in this case, at D:\keystore.jks, with password 'test'
		store.load(new FileInputStream("D:\\keystore.jks"), "test".toCharArray()); 

		//init the key store, along with the password 'test'
		kmf.init(store, "test".toCharArray());
		KeyManager[] keyManagers = new KeyManager[1];
		keyManagers = kmf.getKeyManagers();

		//Init the trust manager factory
		TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());

		//It will reference the same key store as the key managers
		TrustManager[] trustManagers = tmf.getTrustManagers();
		ssl.init(keyManagers, trustManagers, new SecureRandom());

		//Init a configuration with our SSL context
		HttpsConfigurator configurator = new HttpsConfigurator(ssl);

		//Create a server on localhost, port 443 (https port)
		HttpsServer httpsServer = HttpsServer.create(new InetSocketAddress("localhost", 443), 443);
		//Create a context so our service will be available under this context
		HttpContext context = httpsServer.createContext("/test");

		//Finally, use the created context to publish the service


And voilà! That should be enough to your service be available under SSL. With this code, the wsdl of the service should be available under https://localhost:443/test?wsdl.

Please note that, at the time that I developed this service, I had some trouble with the generated WSDL, specifically with the port address and references to schema files. A reasonable work around for this problem (if you have it too) is to download the files (WSDL, schemas, and so on) and fix it by hand.

See ya!


How to dynamically select a certificate alias when invoking web services

08/09/2010 16 comments

Hi, boys and girls! First of all, I would like to say that, yes, this blog´s posts are gonna be all written in English, so they can affect more people around the world. That said, I also would like to say that, although the language has changed, the content is gonna be the same, so I will write and, where it fits, make a critical analysis on the solution.

So, what is the problem?

Web services that use certificates are specially tough to invoke. Along with the complexity that involves almost everything that concern to web services, it also involves the complexity that involves almost everything that concerns to secure communication over the web. So, putting these problems together may give a very strong headache to whoever that wishes to invoke secure web services in Java. Invoking services in a secure way is relatively easy when they do not use more than one certificate in the same VM. But, when it involves more than one certificate, it may be useful to give aliases to the certificates, and to have the ability to select between these certificates in runtime. Also, it may be useful even to change from keystore to keystore in runtime. So, the intent, here, is to provide a simple solution to this problem.

What am I gonna need?

First, you need to assemble a key store and a trust store. I´m not gonna show how to do it here; however, the reader may google it (using a query like this one) to find out how to do it. Second, you must (obviously) have the contract for the service to be invoked. Be warned that, probably, you won´t be able to access it directly, because it will be protected by HTTPS. So, get in touch with the responsibles for the service that you want to invoke. Third, and finally, remember to read carefully the analysis that I am providing at the end of the text (the penalty for not accomplishing this requirement may be an incompatibility between environments).

I´m aware of the requirements, let´s go!

The code consists of the following pieces:

  • A SSL Socket Factory Generator
  • An Alias Selector
  • A Service Invoker

The code for the SSL Socket Factory Generator is like the one below:

import java.util.logging.Logger;


public class SSLSocketFactoryGenerator {
	private String alias = null;
	private String keyStore = null;
	private String trustStore = null;
	public SSLSocketFactoryGenerator (String alias, String keyStore, String trustStore) {
		if (alias == null)
			throw new IllegalArgumentException("The alias may not be null");
		this.alias = alias;
		this.keyStore = keyStore;
		this.trustStore = trustStore;


	public SSLSocketFactory getSSLSocketFactory() throws IOException, GeneralSecurityException {
		KeyManager[] keyManagers = getKeyManagers();
		TrustManager[] trustManagers =getTrustManagers();
		//For each key manager, check if it is a X509KeyManager (because we will override its 		//functionality
		for (int i=0; i<keyManagers.length; i++) {
			if (keyManagers[i] instanceof X509KeyManager) {
				keyManagers[i]=new AliasSelectorKeyManager((X509KeyManager)keyManagers[i], alias);

		SSLContext context=SSLContext.getInstance("SSL");
		context.init(keyManagers, trustManagers, null);

		SSLSocketFactory ssf=context.getSocketFactory();
    		return ssf;
	public String getKeyStorePassword() {
		return "keyStorePassword";
	public String getTrustStorePassword() {
		return "trustStorePassword";

	public String getKeyStore() {
		return keyStore;

	public String getTrustStore() {
		return trustStore;

	private KeyManager[] getKeyManagers()
	throws IOException, GeneralSecurityException
		//Init a key store with the given file.
		String alg=KeyManagerFactory.getDefaultAlgorithm();
		KeyManagerFactory kmFact=KeyManagerFactory.getInstance(alg);

		FileInputStream fis=new FileInputStream(getKeyStore());
		KeyStore ks=KeyStore.getInstance("jks");
		ks.load(fis, getKeyStorePassword().toCharArray());

		//Init the key manager factory with the loaded key store
		kmFact.init(ks,  getKeyStorePassword().toCharArray());

		KeyManager[] kms=kmFact.getKeyManagers();
		return kms;

	protected TrustManager[] getTrustManagers() throws IOException, GeneralSecurityException
		String alg=TrustManagerFactory.getDefaultAlgorithm();
		TrustManagerFactory tmFact=TrustManagerFactory.getInstance(alg);
		FileInputStream fis=new FileInputStream(getTrustStore());
		KeyStore ks=KeyStore.getInstance("jks");
		ks.load(fis, getTrustStorePassword().toCharArray());


		TrustManager[] tms=tmFact.getTrustManagers();
		return tms;

So, the SSLSocketFactory will act as a provider for our secure sockets. Note that the class AliasSelectorKeyManager is our alias selector. It´s code is shown below:



public class AliasSelectorKeyManager implements X509KeyManager{

	private X509KeyManager sourceKeyManager=null;
	private String alias;

	public AliasSelectorKeyManager(X509KeyManager keyManager, String alias)
		this.alias = alias;


	public String chooseClientAlias(String[] keyType, Principal[] issuers,
			Socket socket)
		boolean aliasFound=false;

		//Get all aliases from the key manager. If any matches with the managed alias,
		//then return it.
		//If the alias has not been found, return null (and let the API to handle it, 
		//causing the handshake to fail).

		for (int i=0; i<keyType.length && !aliasFound; i++) {
			String[] validAliases=sourceKeyManager.getClientAliases(keyType[i], issuers);
			if (validAliases!=null) {
				for (int j=0; j<validAliases.length && !aliasFound; j++) {
					if (validAliases[j].equals(alias)) aliasFound=true;

		if (aliasFound) {
			return alias;
		else return null;

	public String chooseServerAlias(String keyType, Principal[] issuers,
			Socket socket)
		return sourceKeyManager.chooseServerAlias(keyType, issuers, socket);

	public X509Certificate[] getCertificateChain(String alias)
		return sourceKeyManager.getCertificateChain(alias);

	public String[] getClientAliases(String keyType, Principal[] issuers)
		return sourceKeyManager.getClientAliases(keyType, issuers);

	public PrivateKey getPrivateKey(String alias)

		return sourceKeyManager.getPrivateKey(alias);

	public String[] getServerAliases(String keyType, Principal[] issuers)
		return sourceKeyManager.getServerAliases(keyType, issuers);


So, at this point we have a custom SSLSocketFactory, that can generate a custom selection for aliases. The final step is to force our web services to use it. To do so, the trick is to generate a Dispatch, which is a JAX-WS interface responsible for calling web services. The Dispatch may accept custom parameters to do the invocations, and we may pass a SSLSocketFactory as parameter, by using a Sun interface called JAXWSProperties. The code is shown below:

public Dispatch<SOAPMessage> getDispatcher(String alias) throws IOException, GeneralSecurityException {
		String namespace = "";
		String wsdlLocation = "";
		String serviceName = "MyService";
		String portName = "MyServiceSoap";
		String soapActionUri = "";
		String keyStoreLocation = "C:\\chains\\myKeystore.jks";
		String trustStoreLocation = "C:\\chains\\myTrustStore.jks";

		//Load a dispatcher with the givend data.
		Dispatch<SOAPMessage> dispatcher = getDispatcher(wsdlLocation, namespace, serviceName, portName);
		//Create our custom SSLSocketFactory
		SSLSocketFactory socketFactory = new SSLSocketFactoryGenerator().generateSocketFactory(alias, keyStoreLocation, trustStoreLocation);

		//Be aware: don´t use the interface instead !!!!
		dispatcher.getRequestContext().put (, socketFactory);
		dispatcher.getRequestContext().put(BindingProvider.SOAPACTION_URI_PROPERTY, soapActionUri);
		return dispatcher;
	public Dispatch<SOAPMessage> getDispatcher (String wsdl, String namespace, String servicename, String portName){
		try {
			//create a representation of the service
			Service service = Service.create(new URL(wsdl), new QName(
					namespace, servicename));
			final Iterator<QName> ports = service.getPorts();
			QName methodToBeCalled = null;

			//Select the port to be called
			if (portName == null)
				methodToBeCalled =;
			else {
				while (methodToBeCalled == null || !methodToBeCalled.getLocalPart().equals(portName)) {
					methodToBeCalled =;
			//Create the dispatcher, given the data.
			Dispatch<SOAPMessage> dispatch = service.createDispatch(
					methodToBeCalled, SOAPMessage.class, Service.Mode.MESSAGE);

			return dispatch;
		} catch (Exception e) {
			throw new RuntimeException("Error calling web-service", e);

Here, I create the dispatch to invoke the service. All I have to do, now, is to create a SOAPMessage and use the invoke method, on the Dispatch interface, to invoke the web service in a secure way. If it interests the reader, you may improve the code to use some sort of JAXB piece to create a SOAPMessage from an object.

What should I pay attention to?

The reader must be aware that JAXWSProperties is part of a Sun library and, so, may not work with some application servers and/or Virtual Machine implementations. I tested it using Sun´s JDK 1.6.0_20, with a JBoss AS 5 (which already has the JAR that contains JAXWSProperties). Also, be aware that the solution presented here is not easy to use, and the reader may be interested in creating some sort of Object-to-SOAPMessage translator (maybe using Reflections?). Finally, be sure that speed is not critical, because this code is going to generate a new SSLSocketFactory (including a IO call) to every call, so it may be more interesting to use some kind of cache (of the SSLSocketFactory), in order not to create a new one at every call, but to reuse them.

Nice coding!