/**
 * MySSLSocketFactory.java
 *
 * @author Created by Donald Fraser
 */

package MyOrganisation.MyClientApp.ssl;


import java.io.InputStream;
import java.io.StringReader;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.Certificate;
import java.security.KeyStore;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.SSLSocket;
import java.util.ArrayList;


/**
 * Provides a wrapper to a real SSLSocketFactory delegating all calls
 * to the contained instance. The contained instance is created in
 * the Constructor and will validate against any server certificate that
 * was signed by the Your Companies CA.
 */
public final class MySSLSocketFactory extends SSLSocketFactory
{
	/** The global ssl socket factory. We only create or attempt to create
	 * it once **/
    private static SSLSocketFactory g_factory;
	/** The global error that occured when creating the ssl socket factory **/
	private static IOException g_IOException;
	
	private static String [] g_saEnabledCiphers;
	
	/**
	 * This is an exaustive list of acceptable ciphers.
	 * Note: CISX server certificates are only signed using RSA, as apposed to
	 * DSS.
	 **/
	private static final String [] ACCEPTABLE_CIPHERS = {
		"SSL_RSA_WITH_RC4_128_SHA",
		"TLS_DHE_RSA_WITH_AES_128_CBC_SHA",
		"TLS_RSA_WITH_AES_128_CBC_SHA",
		"TLS_DHE_RSA_WITH_AES_256_CBC_SHA",
		};

	
	/**
	 * Constructor for creating the ssl socket factory.
	 * We only attempt to create the factory once, if successful it is stored
	 * in the global member variable<code>g_factory</code>.
	 **/
	public MySSLSocketFactory()
	{
		createInstance();
	}

	/** Method to create the global ssl factory object
	 * We only attempt to create the factory once, if successful it is stored
	 * in the global member variable<code>g_factory</code>.
	 **/
	public static void createInstance()
	{
		if (g_factory != null || g_IOException != null)
			return;
		
		CertificateFactory cf = null;
		try
		{
			 cf = CertificateFactory.getInstance("X.509");
		}
		catch (CertificateException e)
		{
			g_IOException = new IOException("Failed to create X.509 certificate factory - " + e.getMessage());
			g_IOException.initCause(e);
			return;
		}
		
		/* This is the public CISX root CA certificate that was used to sign
		 the server certificates.*/
		final StringBuffer sCertificate = new StringBuffer(1390);
		// Copy your generated certificate - LINE for LINE into the string buffer
		sCertificate.append("-----BEGIN CERTIFICATE-----\n");
		sCertificate.append("Your certificate code goes here\n");
		sCertificate.append("-----END CERTIFICATE-----\n");
		
		javax.net.ssl.SSLContext ctx = null;
        try
		{
			final Certificate cert = cf.generateCertificate(new StringInputStream(sCertificate.toString()));

			KeyStore ks = KeyStore.getInstance("jks");
			char [] pass = new char[6];
			ks.load(null, pass); // initialise keystore with null stream
			ks.setCertificateEntry("CA CISX", cert);
			
			KeyManagerFactory mgr = KeyManagerFactory.getInstance("SunX509");
			mgr.init(ks, pass);
			
			TrustManagerFactory tmgr = TrustManagerFactory.getInstance("SunX509");
			tmgr.init(ks);

            ctx = SSLContext.getInstance("TLS");
			ctx.init(mgr.getKeyManagers(), tmgr.getTrustManagers(), null);
			// use the following if you don't want to validate the server!
			/*
             ctx.init( 	null,
					  	new javax.net.ssl.TrustManager[]
						{
							
						   new javax.net.ssl.X509TrustManager()
							{
								public void checkClientTrusted(X509Certificate[] p1, String p2) throws CertificateException
								{
								}
								
								public void checkServerTrusted(X509Certificate[] p1, String p2) throws CertificateException
								{
								}
															
								public X509Certificate[] getAcceptedIssuers()
								{
									return new X509Certificate[0];
								}
							}
					   	},
						null);
			 */
        }
		catch (Exception e)
		{
			g_IOException = new IOException("Failed to create SSL Context - " + e.getMessage());
			g_IOException.initCause(e);
			return;
		}
		
		SSLSocketFactory factory = ctx.getSocketFactory();
		
		// now get the list of available acceptable ciphers to enable
		String [] strCiphers = factory.getSupportedCipherSuites();
		ArrayList<String> alAvailable = new ArrayList();

		for (int a = 0; a < ACCEPTABLE_CIPHERS.length; a++)
			for (int i=strCiphers.length; --i >= 0;)
			{
				// Determine if pattern exists in input
				if (ACCEPTABLE_CIPHERS[a].compareTo(strCiphers[i]) == 0)
				  alAvailable.add(strCiphers[i]);
			}
		if (alAvailable.size() > 0)
			g_saEnabledCiphers = alAvailable.toArray(new String[alAvailable.size()]);
		else
			g_saEnabledCiphers = new String[] {"SSL_NULL_WITH_NULL_NULL"};

		g_factory = factory;
			
		/*
		//list enabled acceptable ciphers
		for (int i=0; i < g_saEnabledCiphers.length; i++)
        	System.out.println(g_saEnabledCiphers[i]);
		System.out.println();
		 */
	}
	
    public Socket createSocket(InetAddress host, int port) throws IOException
	{
		if (g_IOException != null)
			throw g_IOException;
		SSLSocket s = (SSLSocket)g_factory.createSocket(host, port);
		s.setEnabledCipherSuites(g_saEnabledCiphers);
		return s;
    }

    public Socket createSocket(String host, int port) throws IOException
	{
		if (g_IOException != null)
			throw g_IOException;
		SSLSocket s = (SSLSocket)g_factory.createSocket(host, port);
		s.setEnabledCipherSuites(g_saEnabledCiphers);
		return s;
    }

    public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException
	{
		if (g_IOException != null)
			throw g_IOException;
		SSLSocket s = (SSLSocket)g_factory.createSocket(host, port, localHost, localPort);
		s.setEnabledCipherSuites(g_saEnabledCiphers);
		return s;
    }

    public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException
	{
		if (g_IOException != null)
			throw g_IOException;
		SSLSocket s = (SSLSocket)g_factory.createSocket(address, port, localAddress, localPort);
		s.setEnabledCipherSuites(g_saEnabledCiphers);
		return s;
    }

    public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException
	{
		if (g_IOException != null)
			throw g_IOException;
		SSLSocket s = (SSLSocket)g_factory.createSocket(socket, host, port, autoClose);
		s.setEnabledCipherSuites(g_saEnabledCiphers);
		return s;
    }

    public String[] getDefaultCipherSuites()
	{
		if (g_factory == null)
			return new String[] {};
        return g_factory.getDefaultCipherSuites();
    }

    public String[] getSupportedCipherSuites()
	{
		if (g_factory == null)
			return new String[] {};
        return g_factory.getSupportedCipherSuites();
    }
	
	/** Class to represent a StringStream by wrapping StringReader into
	 * the InputStream class.
	 **/
	private final static class StringInputStream extends InputStream
	{
		private StringReader m_StringReader;
		
		public StringInputStream(String s)
		{
			super();
			m_StringReader = new StringReader(s);
		}
		
		public int read() throws IOException
		{
			return m_StringReader.read();
		}
	}
}


