/* * Copyright 2006-2007 Sun Microsystems, Inc. All Rights Reserved. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ package ssljsr262; import java.io.FileInputStream; import java.security.KeyStore; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManagerFactory; /** * Class that builds an SSLContext based on java properties. */ public class TestSSLContext { public static SSLContext getInstance(String protocol) throws Exception { // Retreive java properties String keystore_password = System.getProperty( "javax.net.ssl.keyStorePassword"); String truststore_password = System.getProperty( "javax.net.ssl.trustStorePassword"); String keystore_file = System.getProperty( "javax.net.ssl.keyStore"); String truststore_file = System.getProperty( "javax.net.ssl.trustStore"); char[] keystore_password_char = null; char[] truststore_password_char = null; KeyStore keyStore = null; KeyStore trustStore = null; KeyManagerFactory kmf = null; TrustManagerFactory tmf = null; SSLContext sslContext = null; if (keystore_password != null) { keystore_password_char = keystore_password.toCharArray(); // The system will return the most preferred implementation // of the specified keystore type available in the environment. keyStore = KeyStore.getInstance("JKS"); keyStore.load(new FileInputStream(keystore_file), keystore_password_char); // Generates a KeyManagerFactory object that implements // the specified key management algorithm. kmf = KeyManagerFactory.getInstance("SunX509"); kmf.init(keyStore, keystore_password_char); } if (truststore_password != null) { truststore_password_char = truststore_password.toCharArray(); trustStore = KeyStore.getInstance("JKS"); trustStore.load(new FileInputStream(truststore_file), truststore_password_char); // Generates a TrustManagerFactory object that implements // the specified trust management algorithm. tmf = TrustManagerFactory.getInstance("SunX509"); tmf.init(trustStore); } // Generates a SSLContext object that implements // the specified secure socket protocol. sslContext = SSLContext.getInstance(protocol); sslContext.init( (kmf == null ? null : kmf.getKeyManagers()), (tmf == null ? null : tmf.getTrustManagers()), null); return sslContext; } }