import java.io.*;
import java.net.*;
import javax.net.ssl.*;
import java.security.*;

public class installCert implements X509TrustManager
{
	//-----------------------------------------------------------------------
	// Member Variables
	//-----------------------------------------------------------------------
	private String m_sServer;
	private String m_sPassword;
	private String m_sAlias;

	//=======================================================================
	// X509TrustManager implementation
	//=======================================================================

	//-----------------------------------------------------------------------

	public
	boolean
	checkClientTrusted
	(
		java.security.cert.X509Certificate []chain
	)
	{
		return true;
	}

	//-----------------------------------------------------------------------

	public
	boolean
	isServerTrusted
	(
		java.security.cert.X509Certificate []chain
	)
	{
		for(int i=0; i<chain.length; i++)
		{
			try
			{
				KeyStore ks = KeyStore.getInstance("JKS", "SUN");
				File f = new File(System.getProperty("user.home") + "/.keystore");
				FileInputStream fis = new FileInputStream(f);

				ks.load(fis, m_sPassword.toCharArray());
				fis.close();
	
				ks.setCertificateEntry(m_sAlias, chain[i]);
				ks.store
				(
					new FileOutputStream(new File(System.getProperty("user.home") + "/.keystore") ),
					m_sPassword.toCharArray()
				);
			}
			catch(Exception ex)
			{
				System.out.println("Exception caught: " + ex);
			}
		}
		return true;
	}

	//-----------------------------------------------------------------------

	public
	boolean
	isClientTrusted
	(
		java.security.cert.X509Certificate []chain
	)
	{
		return true;
	}

	//-----------------------------------------------------------------------

	public
	java.security.cert.X509Certificate[]
	getAcceptedIssuers
	(
	)
	{
		return null;
	}

	//-----------------------------------------------------------------------

	public
	void
	checkClientTrusted
	(
		java.security.cert.X509Certificate []chain,
		String authType
	)
	{
	}

	//-----------------------------------------------------------------------

	public
	void
	checkServerTrusted
	(
		java.security.cert.X509Certificate []chain,
		String authType
	)
	{
		for(int i=0; i<chain.length; i++)
		{
			try
			{
				KeyStore ks = KeyStore.getInstance("JKS", "SUN");
				File f = new File(System.getProperty("user.home") + "/.keystore");
				//-------------------------------------------------------
				// Try to open the current keystore from file
				//-------------------------------------------------------
				FileInputStream fis = new FileInputStream(f);
				ks.load(fis, m_sPassword.toCharArray());
				fis.close();
	
				//-----------------------------------------------------------
				// Add Certificate Entry
				//-----------------------------------------------------------
				ks.setCertificateEntry(m_sAlias, chain[i]);
				ks.store
				(
					new FileOutputStream(new File(System.getProperty("user.home") + "/.keystore") ),
					m_sPassword.toCharArray()
				);
			}
			catch(Exception ex)
			{
				System.out.println("Exception caught: " + ex);
			}
		}
	}

	//=======================================================================
	// installCert methods
	//=======================================================================

	//-----------------------------------------------------------------------

	public
	static void
	usage
	(
	)
	{
		System.out.println("Usage: installCert server keystore_password keystore_alias");
	}

	//-----------------------------------------------------------------------

	public
	boolean
	validateParams
	(
	)
	{
		boolean bValid = true;
		try
		{
			//-----------------------------------------------------------
			// Check the password
			//-----------------------------------------------------------
			KeyStore ks = KeyStore.getInstance("JKS", "SUN");
			File f = new File(System.getProperty("user.home") + "/.keystore");
			try
			{
				//-------------------------------------------------------
				// Try to open the current keystore from file
				//-------------------------------------------------------
				FileInputStream fis = new FileInputStream(f);
	
				try
				{
					ks.load(fis, m_sPassword.toCharArray());
				}
				catch(Exception ex)
				{
					System.out.println("ERROR: Incorrect keystore password");
					bValid = false;
				}
				fis.close();
			}
			catch (java.io.FileNotFoundException ex)
			{
				//-------------------------------------------------------
				// keystore doesn't exist so create new one
				//-------------------------------------------------------
				ks.load(null, m_sPassword.toCharArray());
			}

			if ( bValid )
			{
				//-----------------------------------------------------------
				// Check to see if alias already exists in the given keystore
				//-----------------------------------------------------------
				if ( ks.containsAlias(m_sAlias) )
				{
					System.out.println("Keystore already contains alias " + m_sAlias);
					bValid = false;
				}
			}
		}
		catch(Exception ex)
		{
			System.out.println("Exception: " + ex);
		}

		return bValid;
	}

	//-----------------------------------------------------------------------

	public
	void
	getCert
	(
		String sServer, 
		String sPassword, 
		String sAlias
	)
	{
		m_sServer = sServer;
		m_sPassword = sPassword;
		m_sAlias = sAlias;

		// Check password
		if ( ! validateParams() )
		{
			return;
		}

		//-------------------------------------------------------------------
		// use Sun's reference implementation of a URL handler
		// for the "https" URL protocol type.
		//-------------------------------------------------------------------
		//System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
		//System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");

		SSLSocketFactory sslSF = null;
		TrustManager[] tm = {this};

		try
		{
			SSLContext sslContext = SSLContext.getInstance("SSL");

			//-------------------------------------------------------------------
			// register our implementation of TrustManager
			//-------------------------------------------------------------------
			sslContext.init(null, tm, new java.security.SecureRandom());
			sslSF = sslContext.getSocketFactory();
		}
		catch(Exception ex)
		{
			System.out.println("Exception caught: " + ex);
		}

		URL url = null;
		try
		{
			url = new URL("https://" + m_sServer);
		}
		catch(MalformedURLException ex)
		{
			System.out.println("Malformed URL: " + ex);	
		}

		try
		{
			URLConnection uCon = url.openConnection();
			((javax.net.ssl.HttpsURLConnection)uCon).setSSLSocketFactory(sslSF);

			//---------------------------------------------------------------
			// getInputStream results in the isServerTrusted() method being
			// invoked it will throw an exception since we haven't provided
			// username/password. That doesn't matter as we already have the
			// server cert.
			//---------------------------------------------------------------
			InputStream is = uCon.getInputStream();
		}
		catch(Exception ex)
		{
			// Toss it!
		}
	}

	//=======================================================================
	// Main entry point
	//=======================================================================

	//-----------------------------------------------------------------------

	public static void
	main
	(
		String [] args
	)
	{
		if ( args.length < 3 )
		{
			usage();
		}
		else
		{
			try
			{
				installCert ic = new installCert();
				ic.getCert(args[0], args[1], args[2]);
			}
			catch(Exception ex)
			{
				System.out.println("Exception caught: " + ex);
			}
		}
	}
}

/* End Of File */

