Example usage for javax.net.ssl SSLContext getSocketFactory

List of usage examples for javax.net.ssl SSLContext getSocketFactory

Introduction

In this page you can find the example usage for javax.net.ssl SSLContext getSocketFactory.

Prototype

public final SSLSocketFactory getSocketFactory() 

Source Link

Document

Returns a SocketFactory object for this context.

Usage

From source file:com.photon.phresco.framework.impl.SCMManagerImpl.java

void additionalAuthentication(String passPhrase) {
    final String passwordPhrase = passPhrase;
    JschConfigSessionFactory sessionFactory = new JschConfigSessionFactory() {
        @Override/*from   w  w w  .  j a va  2s .co m*/
        protected void configure(OpenSshConfig.Host hc, Session session) {
            CredentialsProvider provider = new CredentialsProvider() {
                @Override
                public boolean isInteractive() {
                    return false;
                }

                @Override
                public boolean supports(CredentialItem... items) {
                    return true;
                }

                @Override
                public boolean get(URIish uri, CredentialItem... items) throws UnsupportedCredentialItem {
                    for (CredentialItem item : items) {
                        if (item instanceof CredentialItem.StringType) {
                            ((CredentialItem.StringType) item).setValue(passwordPhrase);
                        }
                    }
                    return true;
                }
            };
            UserInfo userInfo = new CredentialsProviderUserInfo(session, provider);
            // Unknown host key for ssh
            java.util.Properties config = new java.util.Properties();
            config.put(STRICT_HOST_KEY_CHECKING, NO);
            session.setConfig(config);

            session.setUserInfo(userInfo);
        }
    };

    SshSessionFactory.setInstance(sessionFactory);

    /*
     * Enable clone of https url by trusting those urls
     */
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

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

        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }
    } };

    final String https_proxy = System.getenv(HTTPS_PROXY);
    final String http_proxy = System.getenv(HTTP_PROXY);

    ProxySelector.setDefault(new ProxySelector() {
        final ProxySelector delegate = ProxySelector.getDefault();

        @Override
        public List<Proxy> select(URI uri) {
            // Filter the URIs to be proxied

            if (uri.toString().contains(HTTPS) && StringUtils.isNotEmpty(http_proxy) && http_proxy != null) {
                try {
                    URI httpsUri = new URI(https_proxy);
                    String host = httpsUri.getHost();
                    int port = httpsUri.getPort();
                    return Arrays.asList(new Proxy(Type.HTTP, InetSocketAddress.createUnresolved(host, port)));
                } catch (URISyntaxException e) {
                    if (debugEnabled) {
                        S_LOGGER.debug("Url exception caught in https block of additionalAuthentication()");
                    }
                }
            }

            if (uri.toString().contains(HTTP) && StringUtils.isNotEmpty(http_proxy) && http_proxy != null) {
                try {
                    URI httpUri = new URI(http_proxy);
                    String host = httpUri.getHost();
                    int port = httpUri.getPort();
                    return Arrays.asList(new Proxy(Type.HTTP, InetSocketAddress.createUnresolved(host, port)));
                } catch (URISyntaxException e) {
                    if (debugEnabled) {
                        S_LOGGER.debug("Url exception caught in http block of additionalAuthentication()");
                    }
                }
            }

            // revert to the default behaviour
            return delegate == null ? Arrays.asList(Proxy.NO_PROXY) : delegate.select(uri);
        }

        @Override
        public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
            if (uri == null || sa == null || ioe == null) {
                throw new IllegalArgumentException("Arguments can't be null.");
            }
        }
    });

    // Install the all-trusting trust manager
    try {
        SSLContext sc = SSLContext.getInstance(SSL);
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (GeneralSecurityException e) {
        e.getLocalizedMessage();
    }
}

From source file:org.apache.nifi.cluster.coordination.http.replication.okhttp.OkHttpReplicationClient.java

private Tuple<SSLSocketFactory, X509TrustManager> createSslSocketFactory(final NiFiProperties properties) {
    final SSLContext sslContext = SslContextFactory.createSslContext(properties);

    if (sslContext == null) {
        return null;
    }/*from  w  ww.  ja  v a2  s  .c o  m*/

    try {
        final KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("X509");

        // initialize the KeyManager array to null and we will overwrite later if a keystore is loaded
        KeyManager[] keyManagers = null;

        // we will only initialize the keystore if properties have been supplied by the SSLContextService
        final String keystoreLocation = properties.getProperty(NiFiProperties.SECURITY_KEYSTORE);
        final String keystorePass = properties.getProperty(NiFiProperties.SECURITY_KEYSTORE_PASSWD);
        final String keystoreType = properties.getProperty(NiFiProperties.SECURITY_KEYSTORE_TYPE);

        // prepare the keystore
        final KeyStore keyStore = KeyStore.getInstance(keystoreType);

        try (FileInputStream keyStoreStream = new FileInputStream(keystoreLocation)) {
            keyStore.load(keyStoreStream, keystorePass.toCharArray());
        }

        keyManagerFactory.init(keyStore, keystorePass.toCharArray());
        keyManagers = keyManagerFactory.getKeyManagers();

        // we will only initialize the truststure if properties have been supplied by the SSLContextService
        // load truststore
        final String truststoreLocation = properties.getProperty(NiFiProperties.SECURITY_TRUSTSTORE);
        final String truststorePass = properties.getProperty(NiFiProperties.SECURITY_TRUSTSTORE_PASSWD);
        final String truststoreType = properties.getProperty(NiFiProperties.SECURITY_TRUSTSTORE_TYPE);

        KeyStore truststore = KeyStore.getInstance(truststoreType);
        truststore.load(new FileInputStream(truststoreLocation), truststorePass.toCharArray());
        trustManagerFactory.init(truststore);

        // TrustManagerFactory.getTrustManagers returns a trust manager for each type of trust material. Since we are getting a trust manager factory that uses "X509"
        // as it's trust management algorithm, we are able to grab the first (and thus the most preferred) and use it as our x509 Trust Manager
        //
        // https://docs.oracle.com/javase/8/docs/api/javax/net/ssl/TrustManagerFactory.html#getTrustManagers--
        final X509TrustManager x509TrustManager;
        TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
        if (trustManagers[0] != null) {
            x509TrustManager = (X509TrustManager) trustManagers[0];
        } else {
            throw new IllegalStateException("List of trust managers is null");
        }

        // if keystore properties were not supplied, the keyManagers array will be null
        sslContext.init(keyManagers, trustManagerFactory.getTrustManagers(), null);

        final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
        return new Tuple<>(sslSocketFactory, x509TrustManager);
    } catch (final Exception e) {
        throw new RuntimeException(
                "Failed to create SSL Socket Factory for replicating requests across the cluster");
    }
}

From source file:org.apache.servicemix.http.processors.CommonsHttpSSLSocketFactory.java

protected final void createUnmanagedFactory(SslParameters ssl) throws Exception {
    SSLContext context;
    if (ssl.getProvider() == null) {
        context = SSLContext.getInstance(ssl.getProtocol());
    } else {//from  w  ww  .  ja v a2s.  c o  m
        context = SSLContext.getInstance(ssl.getProtocol(), ssl.getProvider());
    }
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(ssl.getKeyManagerFactoryAlgorithm());
    String keyStore = ssl.getKeyStore();
    if (keyStore == null) {
        keyStore = System.getProperty("javax.net.ssl.keyStore");
        if (keyStore == null) {
            throw new IllegalArgumentException(
                    "keyStore or system property javax.net.ssl.keyStore must be set");
        }
    }
    if (keyStore.startsWith("classpath:")) {
        try {
            String res = keyStore.substring(10);
            URL url = new ClassPathResource(res).getURL();
            keyStore = url.toString();
        } catch (IOException e) {
            throw new JBIException("Unable to find keyStore " + keyStore, e);
        }
    }
    String keyStorePassword = ssl.getKeyStorePassword();
    if (keyStorePassword == null) {
        keyStorePassword = System.getProperty("javax.net.ssl.keyStorePassword");
        if (keyStorePassword == null) {
            throw new IllegalArgumentException(
                    "keyStorePassword or system property javax.net.ssl.keyStorePassword must be set");
        }
    }
    String trustStore = ssl.getTrustStore();
    String trustStorePassword = null;
    if (trustStore == null) {
        trustStore = System.getProperty("javax.net.ssl.trustStore");
    }
    if (trustStore != null) {
        if (trustStore.startsWith("classpath:")) {
            try {
                String res = trustStore.substring(10);
                URL url = new ClassPathResource(res).getURL();
                trustStore = url.toString();
            } catch (IOException e) {
                throw new JBIException("Unable to find trustStore " + trustStore, e);
            }
        }
        trustStorePassword = ssl.getTrustStorePassword();
        if (trustStorePassword == null) {
            trustStorePassword = System.getProperty("javax.net.ssl.trustStorePassword");
            if (trustStorePassword == null) {
                throw new IllegalArgumentException(
                        "trustStorePassword or system property javax.net.ssl.trustStorePassword must be set");
            }
        }
    }
    KeyStore ks = KeyStore.getInstance(ssl.getKeyStoreType());
    ks.load(Resource.newResource(keyStore).getInputStream(), keyStorePassword.toCharArray());
    keyManagerFactory.init(ks,
            ssl.getKeyPassword() != null ? ssl.getKeyPassword().toCharArray() : keyStorePassword.toCharArray());
    if (trustStore != null) {
        KeyStore ts = KeyStore.getInstance(ssl.getTrustStoreType());
        ts.load(Resource.newResource(trustStore).getInputStream(), trustStorePassword.toCharArray());
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(ssl.getTrustManagerFactoryAlgorithm());
        trustManagerFactory.init(ts);
        context.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(),
                new java.security.SecureRandom());
    } else {
        context.init(keyManagerFactory.getKeyManagers(), null, new java.security.SecureRandom());
    }
    factory = context.getSocketFactory();
}

From source file:org.jivesoftware.smack.XMPPConnection.java

/**
 * The server has indicated that TLS negotiation can start. We now need to secure the
 * existing plain connection and perform a handshake. This method won't return until the
 * connection has finished the handshake or an error occured while securing the connection.
 *
 * @throws Exception if an exception occurs.
 */// w w  w  . j  a  v  a 2  s .c o  m
void proceedTLSReceived() throws Exception {
    SSLContext context = SSLContext.getInstance("TLS");
    KeyStore ks = null;
    KeyManager[] kms = null;
    PasswordCallback pcb = null;

    if (config.getCallbackHandler() == null) {
        ks = null;
    } else {
        //System.out.println("Keystore type: "+configuration.getKeystoreType());
        if (config.getKeystoreType().equals("NONE")) {
            ks = null;
            pcb = null;
        } else if (config.getKeystoreType().equals("PKCS11")) {
            try {
                Constructor c = Class.forName("sun.security.pkcs11.SunPKCS11")
                        .getConstructor(InputStream.class);
                String pkcs11Config = "name = SmartCard\nlibrary = " + config.getPKCS11Library();
                ByteArrayInputStream config = new ByteArrayInputStream(pkcs11Config.getBytes());
                Provider p = (Provider) c.newInstance(config);
                Security.addProvider(p);
                ks = KeyStore.getInstance("PKCS11", p);
                pcb = new PasswordCallback("PKCS11 Password: ", false);
                this.config.getCallbackHandler().handle(new Callback[] { pcb });
                ks.load(null, pcb.getPassword());
            } catch (Exception e) {
                ks = null;
                pcb = null;
            }
        } else if (config.getKeystoreType().equals("Apple")) {
            ks = KeyStore.getInstance("KeychainStore", "Apple");
            ks.load(null, null);
            //pcb = new PasswordCallback("Apple Keychain",false);
            //pcb.setPassword(null);
        } else {
            ks = KeyStore.getInstance(config.getKeystoreType());
            try {
                pcb = new PasswordCallback("Keystore Password: ", false);
                config.getCallbackHandler().handle(new Callback[] { pcb });
                ks.load(new FileInputStream(config.getKeystorePath()), pcb.getPassword());
            } catch (Exception e) {
                ks = null;
                pcb = null;
            }
        }
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        try {
            if (pcb == null) {
                kmf.init(ks, null);
            } else {
                kmf.init(ks, pcb.getPassword());
                pcb.clearPassword();
            }
            kms = kmf.getKeyManagers();
        } catch (NullPointerException npe) {
            kms = null;
        }
    }

    // Verify certificate presented by the server
    context.init(kms, new javax.net.ssl.TrustManager[] { new ServerTrustManager(getServiceName(), config) },
            new java.security.SecureRandom());
    Socket plain = socket;
    // Secure the plain connection
    socket = context.getSocketFactory().createSocket(plain, plain.getInetAddress().getHostName(),
            plain.getPort(), true);
    socket.setSoTimeout(0);
    socket.setKeepAlive(true);
    // Initialize the reader and writer with the new secured version
    initReaderAndWriter();
    // Proceed to do the handshake
    ((SSLSocket) socket).startHandshake();
    //if (((SSLSocket) socket).getWantClientAuth()) {
    //    System.err.println("Connection wants client auth");
    //}
    //else if (((SSLSocket) socket).getNeedClientAuth()) {
    //    System.err.println("Connection needs client auth");
    //}
    //else {
    //    System.err.println("Connection does not require client auth");
    // }
    // Set that TLS was successful
    usingTLS = true;

    // Set the new  writer to use
    packetWriter.setWriter(writer);
    // Send a new opening stream to the server
    packetWriter.openStream();
}

From source file:net.sf.taverna.t2.security.credentialmanager.impl.CredentialManagerImpl.java

/**
 * Creates SSLSocketFactory based on Credential Manager's Keystore and
 * Truststore but only initalizes Credential Manager when one of the methods
 * needed for creating an HTTPS connection is invoked.
 *///ww w .j a v  a 2s .  c o m
private SSLSocketFactory createSSLSocketFactory() throws CMException {
    SSLContext sc = null;
    try {
        sc = SSLContext.getInstance("SSLv3");
    } catch (NoSuchAlgorithmException e1) {
        throw new CMException("Failed to create SSL socket factory: "
                + "the SSL algorithm was not available from any crypto provider", e1);
    }

    KeyManager[] keyManagers = null;
    try {
        // Create our own KeyManager with (possibly not yet initialised)
        // Taverna's Keystore
        keyManagers = new KeyManager[] { new TavernaKeyManager() };
    } catch (Exception e) {
        throw new CMException("Failed to create SSL socket factory: " + "could not initiate SSL Key Manager",
                e);
    }

    TrustManager[] trustManagers = null;
    try {
        // Create our own TrustManager with (possibly not yet initialised)
        // Taverna's Truststore
        trustManagers = new TrustManager[] { new TavernaTrustManager() };
    } catch (Exception e) {
        throw new CMException("Failed to create SSL socket factory: " + "could not initiate SSL Trust Manager",
                e);
    }

    try {
        sc.init(keyManagers, trustManagers, new SecureRandom());
    } catch (KeyManagementException kmex) {
        throw new CMException("Failed to initiate the SSL socet factory", kmex);
    }

    /*
     * Set the default SSLContext to be used for subsequent SSL sockets from
     * Java
     */
    SSLContext.setDefault(sc);

    /*
     * Create SSL socket to be used for HTTPS connections from the JVM e.g.
     * REST activity that uses Apache HTTP client library
     */
    tavernaSSLSocketFactory = sc.getSocketFactory();

    return tavernaSSLSocketFactory;
}

From source file:carnero.cgeo.original.libs.Base.java

public static void trustAllHosts() {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return new java.security.cert.X509Certificate[] {};
        }/*from ww  w .  j ava2  s  . c  o  m*/

        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }
    } };

    try {
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
        Log.e(Settings.tag, "cgBase.trustAllHosts: " + e.toString());
    }
}

From source file:org.openymsg.network.Session.java

private void trustEveryone() {
    try {//from   w  w  w .j av a  2 s. co m
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(final String hostname, final SSLSession session) {
                return true;
            }
        });
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, new X509TrustManager[] { new X509TrustManager() {
            @Override
            public void checkClientTrusted(final X509Certificate[] chain, final String authType)
                    throws CertificateException {
            }

            @Override
            public void checkServerTrusted(final X509Certificate[] chain, final String authType)
                    throws CertificateException {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        } }, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
    } catch (Exception e) { // should never happen
        e.printStackTrace();
    }
}

From source file:carnero.cgeo.cgBase.java

public static void trustAllHosts() {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return new java.security.cert.X509Certificate[] {};
        }//ww w. ja v a 2s  .  c  om

        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }
    } };

    try {
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
        Log.e(cgSettings.tag, "cgBase.trustAllHosts: " + e.toString());
    }
}

From source file:org.beepcore.beep.profile.tls.jsse.TLSProfileJSSE.java

/**
 * init sets the criteria for which an SSL connection is made when
 * a TLS channel is started for a profile.  It should only be
 * called once.  For the properties, the initiator is defined as
 * the peer who starts the channel for the TLS profile, the
 * listener is the peer that receives the the channel start
 * request, irregardless of which actually started the session.<p>
 *
 * @param config <code>ProfileConfiguration</code> object that
 * contains key value pairs to initialize the TLS layer.  None of
 * these are mandatory, but if you wish communication to be
 * anonymous with no authentication, (i.e., the listener to not
 * send back a certificate), you must set "Listener Anonymous" to
 * "true" and "Initiator Authentication Required" to "false".
 * The meaningful properties that can be set are these:<p>
 * <table>//w  w w.j av a2 s  .c  o m
 * <tr>
 * <td>Listener Anonymous</td><td>(true|false) must be set to false if the
 *   listener will not authenticate itself</td>
 * </tr><tr>
 * <td>Initiator Authentication Required</td><td>(true|false) set if the
 *       initiator should send a certificate and the listener expects a
 *       certificate.</td>
 * </tr><tr>
 * <td>Cipher Suite</td><td><i>not yet implemented.</i>the algorithms that
 *       can be used for encryption, authentication, and key exchange.</td>
 * </tr><tr>
 * <td>Key Algorithm</td><td>key management algorithm. See
 *       {@link com.sun.net.ssl.KeyManagerFactory#getInstance}</td>
 * </tr><tr>
 * <td>Key Provider</td><td>provider of the key management
 *       algorithm.  Defaults to
 *    <code>com.sun.net.ssl.internal.ssl.Provider</code> See
 *       {@link com.sun.net.ssl.KeyManagerFactory#getInstance}</td>
 * </tr><tr>
 * <td>Trust Algorithm</td><td>algorithm to be used by the trust
 *       manager.  See
 *       {@link com.sun.net.ssl.TrustManagerFactory#getInstance}</td>
 * </tr><tr>
 * <td>Trust Provider</td><td>provider of the trust manager.  Defaults to
 *    <code>com.sun.net.ssl.internal.ssl.Provider</code>.  See
 *    {@link com.sun.net.ssl.TrustManagerFactory#getInstance}</td>
 * </tr><tr>
 * <td>Key Store Passphrase</td><td>pass phrase used to encrypt the key
 *    store.  See {@link java.security.KeyStore#load}</td>
 * </tr><tr>
 * <td>Key Store Data Type</td><td>data type of the key store passed in.
 *     "file" is currently the only value accepted, meaning Key Store
 *     is the name of a file containing keys.  See
 *     {@link java.security.KeyStore#load}</td>
 * </tr><tr>
 * <td>Key Store</td><td>value of the key store, dependent on the type in
 *     Key Store Data Type.  See {@link java.security.KeyStore#load}</td>
 * </tr><tr>
 * <td>Key Store Format</td><td>format of the keys within the key store.
 *  Default is "JKS".  See {@link java.security.KeyStore#getInstance}</td>
 * </tr><tr>
 * <td>Key Store Provider</td><td>provider for the key stores.  See
 *     {@link java.security.KeyStore#getInstance}</td>
 * </tr><tr>
 * <td>Trust Store Passphrase</td><td>pass phrase used to encrypt the trust
 *     store.  See {@link java.security.KeyStore#load}</td>
 * </tr><tr>
 * <td>Trust Store Data Type</td><td>data type of the certificates in the
 * trust store.  "file" is currently th only value accepted,
 * meaning the trust store is a file on the local disk.  See
 *     {@link java.security.KeyStore#load}</td>
 * </tr><tr>
 * <td>Trust Store</td><td>value of the trust store, dependent on the type
 *     in Trust
 *     Store Data Type  See {@link java.security.KeyStore#load}</td>
 * </tr><tr>
 * <td>Trust Store Format</td><td>format of the certificates within the
 *     trust store.
 * Default is "JKS".  See {@link java.security.KeyStore#getInstance}</td>
 * </tr><tr>
 * <td>Trust Store Provider</td><td>provider for the trust stores.  See
 *     {@link java.security.KeyStore#getInstance}</td>
 * </tr><tr>
 * <td>Allowed SSL Protocols</td><td>Comma separated list of algorithms 
 * that may be used for SSL/TLS negotiations. By default, this will be 
 * whatever the {@link SSLSocket} implementation supports.
 * @see SSLSocket#getSupportedProtocols()
 * @see SSLSocket#setEnabledProtocols(String[])
 * </tr><tr>
 * </table>
 * @throws BEEPException For any error in the profile configuration, a
 * negative response in the form of a BEEP error will be sent back to the
 * requesting peer.  The session will continue to be open and usable, at
 * least from the standpoint of this peer.
 *
 * @see com.sun.net.ssl.KeyManagerFactory
 * @see com.sun.net.ssl.TrustManagerFactory
 * @see java.security.KeyStore
 * @see com.sun.net.ssl.SSLContext
 */
public StartChannelListener init(String uri, ProfileConfiguration config) throws BEEPException {
    KeyManagerFactory kmf = null;
    KeyManager[] km = null;
    KeyStore ks = null;
    TrustManagerFactory tmf = null;
    TrustManager[] tm = null;
    KeyStore ts = null;
    SSLContext ctx;
    this.sslProtocols = null;

    // set the URI of this instance of the profile
    this.uri = uri;

    try {

        // create an SSL context object
        ctx = SSLContext.getInstance("TLS");
    } catch (java.security.NoSuchAlgorithmException e) {
        throw new BEEPException("TLS Algorithm Not Found. Probable " + "cause is the JSSE provider has not "
                + "been added to the java.security file.");
    }

    try {
        String protocols = config.getProperty(PROPERTY_SSL_PROTOCOLS);
        if (protocols != null) {
            this.sslProtocols = protocols.split(",");
        }
        // initialize the key managers, trust managers, and
        keyAlgorithm = config.getProperty(PROPERTY_KEY_MANAGER_ALGORITHM);
        keyProvider = config.getProperty(PROPERTY_KEY_MANAGER_PROVIDER);
        trustAlgorithm = config.getProperty(PROPERTY_TRUST_MANAGER_ALGORITHM);
        trustProvider = config.getProperty(PROPERTY_TRUST_MANAGER_PROVIDER);
        keyPassphrase = config.getProperty(PROPERTY_KEYSTORE_PASSPHRASE);
        keyStoreType = config.getProperty(PROPERTY_KEYSTORE_TYPE);
        keyStoreName = config.getProperty(PROPERTY_KEYSTORE_NAME);
        keyStoreFormat = config.getProperty(PROPERTY_KEYSTORE_FORMAT, "JKS");
        keyStoreProvider = config.getProperty(PROPERTY_KEYSTORE_PROVIDER);
        trustPassphrase = config.getProperty(PROPERTY_TRUSTSTORE_PASSPHRASE);
        trustStoreType = config.getProperty(PROPERTY_TRUSTSTORE_TYPE);
        trustStoreName = config.getProperty(PROPERTY_TRUSTSTORE_NAME);
        trustStoreFormat = config.getProperty(PROPERTY_TRUSTSTORE_FORMAT, "JKS");
        trustStoreProvider = config.getProperty(PROPERTY_TRUSTSTORE_PROVIDER);

        // determine if the client must authenticate or if the server can
        // 
        needClientAuth = new Boolean(config.getProperty(PROPERTY_CLIENT_AUTHENTICATION, "false"))
                .booleanValue();
        serverAnonymous = new Boolean(config.getProperty(PROPERTY_SERVER_ANONYMOUS, "true")).booleanValue();

        if (keyAlgorithm != null) {
            if (keyProvider != null) {
                kmf = KeyManagerFactory.getInstance(keyAlgorithm, keyProvider);
            } else {
                kmf = KeyManagerFactory.getInstance(keyAlgorithm);
            }

            // add support for a default type of key manager factory?
            if (keyStoreProvider != null) {
                ks = KeyStore.getInstance(keyStoreFormat, keyStoreProvider);
            } else {
                ks = KeyStore.getInstance(keyStoreFormat);
            }

            if (keyStoreType.equals("file")) {
                ks.load(new FileInputStream(keyStoreName), keyPassphrase.toCharArray());
            } else {
                throw new BEEPException(ERR_ILLEGAL_KEY_STORE);
            }

            // initialize the key factory manager 
            kmf.init(ks, keyPassphrase.toCharArray());

            km = kmf.getKeyManagers();
        } else {
            km = null;
        }

        if (trustAlgorithm != null) {
            if (trustProvider != null) {
                tmf = TrustManagerFactory.getInstance(trustAlgorithm, trustProvider);
            } else {
                tmf = TrustManagerFactory.getInstance(trustAlgorithm);
            }

            // add support for a default type of trust manager factory?
            if (trustStoreProvider != null) {
                ts = KeyStore.getInstance(trustStoreFormat, trustStoreProvider);
            } else {
                ts = KeyStore.getInstance(trustStoreFormat);
            }

            if (trustStoreType.equals("file")) {
                ts.load(new FileInputStream(trustStoreName), trustPassphrase.toCharArray());
            } else {
                throw new BEEPException(ERR_ILLEGAL_TRUST_STORE);
            }

            // initialize the trust factory manager 
            tmf.init(ts);

            tm = tmf.getTrustManagers();
        } else {
            tm = null;
        }

        // create a socket factory from the key factories and
        // trust factories created for the algorithms and stores
        // specfied.  No option is given to change the secure
        // random number generator
        ctx.init(km, tm, null);

        socketFactory = ctx.getSocketFactory();

        return this;
    } catch (Exception e) {
        log.error(e);

        throw new BEEPException(e);
    }
}