Example usage for javax.net.ssl SSLContext getServerSocketFactory

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

Introduction

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

Prototype

public final SSLServerSocketFactory getServerSocketFactory() 

Source Link

Document

Returns a ServerSocketFactory object for this context.

Usage

From source file:com.adito.server.jetty.CustomJsseListener.java

protected SSLServerSocketFactory createFactory() throws Exception {
    if (KeyStoreManager.getInstance(KeyStoreManager.DEFAULT_KEY_STORE).isKeyStoreEmpty()) {
        throw new Exception(
                "The keystore does not contain any certificates. Please run the installation wizard (--install).");
    }/* w  ww. j  a v a  2  s.  c  o  m*/
    KeyStore ks = KeyStoreManager.getInstance(KeyStoreManager.DEFAULT_KEY_STORE).getKeyStore();
    String pw = ContextHolder.getContext().getConfig()
            .retrieveProperty(new ContextKey("webServer.keystore.sslCertificate.password"));
    KeyManager[] kma = new KeyManager[] { new CustomKeyManager(pw) };
    TrustManager[] tma = null;
    if (trustManager == null) {
        TrustManagerFactory tm = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tm.init(ks);
        tma = tm.getTrustManagers();
    } else {

        // LDP - Add the existing trust managers so that outgoing certificates are still trusted.
        TrustManagerFactory tm = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tm.init(ks);

        tma = new TrustManager[tm.getTrustManagers().length + 1];
        for (int i = 0; i < tm.getTrustManagers().length; i++) {
            tma[i] = tm.getTrustManagers()[i];
        }
        tma[tma.length - 1] = trustManager;
    }
    SSLContext sslc = SSLContext.getInstance("SSL");
    sslc.init(kma, tma, SecureRandom.getInstance("SHA1PRNG"));
    SSLServerSocketFactory ssfc = sslc.getServerSocketFactory();
    if (log.isInfoEnabled())
        log.info("SSLServerSocketFactory=" + ssfc);
    initialised = true;
    return ssfc;
}

From source file:com.sslexplorer.server.jetty.CustomJsseListener.java

protected SSLServerSocketFactory createFactory() throws Exception {
    if (KeyStoreManager.getInstance(KeyStoreManager.DEFAULT_KEY_STORE).isKeyStoreEmpty()) {
        throw new Exception(
                "The keystore does not contain any certificates. Please run the installation wizard (--install).");
    }//  ww w  .j a  v a  2  s.c  om
    KeyStore ks = KeyStoreManager.getInstance(KeyStoreManager.DEFAULT_KEY_STORE).getKeyStore();
    String pw = ContextHolder.getContext().getConfig()
            .retrieveProperty(new ContextKey("webServer.keystore.sslCertificate.password"));
    KeyManager[] kma = new KeyManager[] { new CustomKeyManager(pw) };
    TrustManager[] tma = null;
    if (trustManager == null) {
        TrustManagerFactory tm = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tm.init(ks);
        tma = tm.getTrustManagers();
    } else {

        // LDP - Add the existing trust managers so that outgoing certificates are still trusted.
        TrustManagerFactory tm = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tm.init(ks);

        tma = new TrustManager[tm.getTrustManagers().length + 1];
        for (int i = 0; i < tm.getTrustManagers().length - 1; i++) {
            tma[i] = tm.getTrustManagers()[i];
        }
        tma[tma.length - 1] = trustManager;
    }
    SSLContext sslc = SSLContext.getInstance("SSL");
    sslc.init(kma, tma, SecureRandom.getInstance("SHA1PRNG"));
    SSLServerSocketFactory ssfc = sslc.getServerSocketFactory();
    if (log.isInfoEnabled())
        log.info("SSLServerSocketFactory=" + ssfc);
    initialised = true;
    return ssfc;
}

From source file:net.lightbody.bmp.proxy.jetty.http.SunJsseListener.java

protected SSLServerSocketFactory createFactory() throws Exception {
    _keystore = System.getProperty(KEYSTORE_PROPERTY, _keystore);

    log.info(KEYSTORE_PROPERTY + "=" + _keystore);

    if (_password == null)
        _password = Password.getPassword(PASSWORD_PROPERTY, null, null);
    log.info(PASSWORD_PROPERTY + "=" + _password.toStarString());

    if (_keypassword == null)
        _keypassword = Password.getPassword(KEYPASSWORD_PROPERTY, null, _password.toString());
    log.info(KEYPASSWORD_PROPERTY + "=" + _keypassword.toStarString());

    KeyStore ks = null;/*from   ww w .ja va2s. com*/

    log.info(KEYSTORE_TYPE_PROPERTY + "=" + _keystore_type);

    if (_keystore_provider_class != null) {
        // find provider.
        // avoid creating another instance if already installed in Security.
        java.security.Provider[] installed_providers = Security.getProviders();
        java.security.Provider myprovider = null;
        for (int i = 0; i < installed_providers.length; i++) {
            if (installed_providers[i].getClass().getName().equals(_keystore_provider_class)) {
                myprovider = installed_providers[i];
                break;
            }
        }
        if (myprovider == null) {
            // not installed yet, create instance and add it
            myprovider = (java.security.Provider) Class.forName(_keystore_provider_class).newInstance();
            Security.addProvider(myprovider);
        }
        log.info(KEYSTORE_PROVIDER_CLASS_PROPERTY + "=" + _keystore_provider_class);
        ks = KeyStore.getInstance(_keystore_type, myprovider.getName());
    } else if (_keystore_provider_name != null) {
        log.info(KEYSTORE_PROVIDER_NAME_PROPERTY + "=" + _keystore_provider_name);
        ks = KeyStore.getInstance(_keystore_type, _keystore_provider_name);
    } else {
        ks = KeyStore.getInstance(_keystore_type);
        log.info(KEYSTORE_PROVIDER_NAME_PROPERTY + "=[DEFAULT]");
    }

    ks.load(new FileInputStream(new File(_keystore)), _password.toString().toCharArray());

    KeyManagerFactory km = KeyManagerFactory.getInstance("SunX509", "SunJSSE");
    km.init(ks, _keypassword.toString().toCharArray());
    KeyManager[] kma = km.getKeyManagers();

    TrustManagerFactory tm = TrustManagerFactory.getInstance("SunX509", "SunJSSE");
    if (_useDefaultTrustStore) {
        tm.init((KeyStore) null);
    } else {
        tm.init(ks);
    }

    TrustManager[] tma = tm.getTrustManagers();

    SSLContext sslc = SSLContext.getInstance("SSL");
    sslc.init(kma, tma, SecureRandom.getInstance("SHA1PRNG"));

    SSLServerSocketFactory ssfc = sslc.getServerSocketFactory();
    log.info("SSLServerSocketFactory=" + ssfc);
    return ssfc;
}

From source file:net.jradius.server.TCPListener.java

public void setConfiguration(ListenerConfigurationItem cfg, boolean noKeepAlive)
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException,
        KeyManagementException, IOException {
    keepAlive = !noKeepAlive;//from w  w  w. j a  v a  2 s .  com
    config = cfg;

    Map props = config.getProperties();

    String s = (String) props.get("port");
    if (s != null)
        port = new Integer(s).intValue();

    s = (String) props.get("backlog");
    if (s != null)
        backlog = new Integer(s).intValue();

    if (keepAlive) {
        s = (String) props.get("keepAlive");
        if (s != null)
            keepAlive = new Boolean(s).booleanValue();
    }

    String useSSL = (String) props.get("useSSL");
    String trustAll = (String) props.get("trustAll");

    if (requiresSSL || "true".equalsIgnoreCase(useSSL)) {
        KeyManager[] keyManagers = null;
        TrustManager[] trustManagers = null;

        String keyManager = (String) props.get("keyManager");

        if (keyManager != null && keyManager.length() > 0) {
            try {
                KeyManager manager = (KeyManager) Configuration.getBean(keyManager);
                keyManagers = new KeyManager[] { manager };
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            String keystore = (String) props.get("keyStore");
            String keystoreType = (String) props.get("keyStoreType");
            String keystorePassword = (String) props.get("keyStorePassword");
            String keyPassword = (String) props.get("keyPassword");

            if (keystore != null) {
                if (keystoreType == null)
                    keystoreType = "pkcs12";

                KeyStore ks = KeyStore.getInstance(keystoreType);
                ks.load(new FileInputStream(keystore),
                        keystorePassword == null ? null : keystorePassword.toCharArray());

                KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
                kmf.init(ks, keyPassword == null ? null : keyPassword.toCharArray());
                keyManagers = kmf.getKeyManagers();
            }
        }

        String trustManager = (String) props.get("trustManager");

        if (trustManager != null && trustManager.length() > 0) {
            try {
                TrustManager manager = (TrustManager) Configuration.getBean(trustManager);
                trustManagers = new TrustManager[] { manager };
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if ("true".equalsIgnoreCase(trustAll)) {
            trustManagers = new TrustManager[] { new X509TrustManager() {
                public void checkClientTrusted(X509Certificate[] chain, String authType) {

                }

                public void checkServerTrusted(X509Certificate[] chain, String authType) {

                }

                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                }
            } };
        } else {
            String keystore = (String) props.get("caStore");
            String keystoreType = (String) props.get("caStoreType");
            String keystorePassword = (String) props.get("caStorePassword");

            if (keystore != null) {
                if (keystoreType == null)
                    keystoreType = "pkcs12";

                KeyStore caKeys = KeyStore.getInstance(keystoreType);
                caKeys.load(new FileInputStream(keystore),
                        keystorePassword == null ? null : keystorePassword.toCharArray());
                TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
                tmf.init(caKeys);
                trustManagers = tmf.getTrustManagers();
            }
        }

        SSLContext sslContext = SSLContext.getInstance("SSLv3");
        sslContext.init(keyManagers, trustManagers, null);

        ServerSocketFactory socketFactory = sslContext.getServerSocketFactory();
        SSLServerSocket sslServerSocket = (SSLServerSocket) socketFactory.createServerSocket(port, backlog);
        serverSocket = sslServerSocket;

        if (sslWantClientAuth)
            sslServerSocket.setWantClientAuth(true);

        if (sslNeedClientAuth)
            sslServerSocket.setNeedClientAuth(true);

        if (sslEnabledProtocols != null)
            sslServerSocket.setEnabledProtocols(sslEnabledProtocols);

        if (sslEnabledCiphers != null)
            sslServerSocket.setEnabledCipherSuites(sslEnabledCiphers);

        usingSSL = true;
    } else {
        serverSocket = new ServerSocket(port, backlog);
    }

    serverSocket.setReuseAddress(true);
    setActive(true);
}

From source file:it.danja.newsmonitor.utils.HttpServer.java

public void init() {

    // Set up the HTTP protocol processor
    HttpProcessor httpproc = HttpProcessorBuilder.create().add(new ResponseDate())
            .add(new ResponseServer("Test/1.1")).add(new ResponseContent()).add(new ResponseConnControl())
            .build();//from w  ww  .ja va  2s  .  c  o m

    // Set up request handlers
    UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper();
    reqistry.register("*", new HttpFileHandler(docRoot));

    // Set up the HTTP service
    httpService = new HttpService(httpproc, reqistry);

    if (port == 8443) {
        // Initialize SSL context
        ClassLoader cl = HttpServer.class.getClassLoader();
        URL url = cl.getResource("my.keystore");
        if (url == null) {
            log.info("HttpServer : Keystore not found");
            System.exit(1);
        }
        KeyStore keystore = null;
        try {
            keystore = KeyStore.getInstance("jks");
        } catch (KeyStoreException e) {

            log.error(e.getMessage());
        }
        try {
            keystore.load(url.openStream(), "secret".toCharArray());
        } catch (NoSuchAlgorithmException e) {

            log.error(e.getMessage());
        } catch (CertificateException e) {

            log.error(e.getMessage());
        } catch (IOException e) {

            log.error(e.getMessage());
        }
        KeyManagerFactory kmfactory = null;
        try {
            kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        } catch (NoSuchAlgorithmException e) {

            log.error(e.getMessage());
        }
        try {
            kmfactory.init(keystore, "secret".toCharArray());
        } catch (UnrecoverableKeyException e) {

            log.error(e.getMessage());
        } catch (KeyStoreException e) {

            log.error(e.getMessage());
        } catch (NoSuchAlgorithmException e) {

            log.error(e.getMessage());
        }
        KeyManager[] keymanagers = kmfactory.getKeyManagers();
        SSLContext sslcontext = null;
        try {
            sslcontext = SSLContext.getInstance("TLS");
        } catch (NoSuchAlgorithmException e) {

            log.error(e.getMessage());
        }
        try {
            sslcontext.init(keymanagers, null, null);
        } catch (KeyManagementException e) {

            log.error(e.getMessage());
        }
        this.sf = sslcontext.getServerSocketFactory();
    }
}

From source file:org.nectarframework.base.service.nanohttp.NanoHttpService.java

/**
 * Creates an SSLSocketFactory for HTTPS. Pass a KeyStore resource with your
 * certificate and passphrase//from www. jav  a 2s. c  om
 */
public ServerSocket makeSSLServerSocket(String keyAndTrustStoreClasspathPath, char[] passphrase)
        throws IOException {
    try {
        KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        InputStream keystoreStream = new FileInputStream(new File(keyAndTrustStoreClasspathPath));

        keystore.load(keystoreStream, passphrase);
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keystore, passphrase);

        SSLServerSocketFactory res = null;
        try {
            TrustManagerFactory trustManagerFactory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init(keystore);
            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
            res = ctx.getServerSocketFactory();

        } catch (Exception e) {
            throw new IOException(e.getMessage());
        }

        SSLServerSocket ss = null;
        ss = (SSLServerSocket) res.createServerSocket();
        ss.setEnabledProtocols(ss.getSupportedProtocols());
        ss.setUseClientMode(false);
        ss.setWantClientAuth(false);
        ss.setNeedClientAuth(false);

        return ss;

    } catch (Exception e) {
        throw new IOException(e.getMessage());
    }
}

From source file:it.jnrpe.server.CBindingThread.java

/**
 * Returns the SSL factory to be used to create the Server Socket
 * @throws KeyStoreException //w w  w.  ja va2 s  .  c  om
 * @throws IOException 
 * @throws FileNotFoundException 
 * @throws CertificateException 
 * @throws UnrecoverableKeyException 
 * @throws KeyManagementException 
 * 
 * @see it.intesa.fi2.client.network.ISSLObjectsFactory#getSSLSocketFactory(String, String, String)
 */
public SSLServerSocketFactory getSSLSocketFactory(String sKeyStoreFile, String sKeyStorePwd,
        String sKeyStoreType) throws KeyStoreException, CertificateException, FileNotFoundException,
        IOException, UnrecoverableKeyException, KeyManagementException {
    if (sKeyStoreFile == null)
        throw new KeyStoreException("KEYSTORE HAS NOT BEEN SPECIFIED");
    if (this.getClass().getClassLoader().getResourceAsStream(sKeyStoreFile) == null)
        throw new KeyStoreException("COULD NOT FIND KEYSTORE '" + sKeyStoreFile + "'");

    if (sKeyStorePwd == null)
        throw new KeyStoreException("KEYSTORE PASSWORD HAS NOT BEEN SPECIFIED");

    SSLContext ctx;
    KeyManagerFactory kmf;

    try {
        ctx = SSLContext.getInstance("SSLv3");

        kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());

        //KeyStore ks = getKeystore(sKeyStoreFile, sKeyStorePwd, sKeyStoreType);
        KeyStore ks = KeyStore.getInstance(sKeyStoreType);
        ks.load(this.getClass().getClassLoader().getResourceAsStream(sKeyStoreFile),
                sKeyStorePwd.toCharArray());

        char[] passphrase = sKeyStorePwd.toCharArray();
        kmf.init(ks, passphrase);
        ctx.init(kmf.getKeyManagers(), null, new java.security.SecureRandom());

    } catch (NoSuchAlgorithmException e) {
        throw new SSLException("Unable to initialize SSLSocketFactory.\n" + e.getMessage());
    }

    return ctx.getServerSocketFactory();
}

From source file:net.lightbody.bmp.proxy.jetty.http.SslListener.java

protected SSLServerSocketFactory createFactory() throws Exception {
    SSLContext context;
    if (_provider == null) {
        context = SSLContext.getInstance(_protocol);
    } else {/*from  w ww.  j  av  a 2s  .  c o m*/
        context = SSLContext.getInstance(_protocol, _provider);
    }

    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(_algorithm);
    KeyStore keyStore = KeyStore.getInstance(_keystoreType);
    keyStore.load(Resource.newResource(_keystore).getInputStream(), _password.toString().toCharArray());
    keyManagerFactory.init(keyStore, _keypassword.toString().toCharArray());

    context.init(keyManagerFactory.getKeyManagers(), null, new java.security.SecureRandom());

    return context.getServerSocketFactory();
}

From source file:org.apache.cassandra.security.SSLFactory.java

public static SSLServerSocket getServerSocket(EncryptionOptions options, InetAddress address, int port)
        throws IOException {
    SSLContext ctx = createSSLContext(options, true);
    SSLServerSocket serverSocket = (SSLServerSocket) ctx.getServerSocketFactory().createServerSocket();
    serverSocket.setReuseAddress(true);/*from   www  . jav  a 2  s  . co m*/
    String[] suits = filterCipherSuites(serverSocket.getSupportedCipherSuites(), options.cipher_suites);
    serverSocket.setEnabledCipherSuites(suits);
    serverSocket.setNeedClientAuth(options.require_client_auth);
    serverSocket.setEnabledProtocols(ACCEPTED_PROTOCOLS);
    serverSocket.bind(new InetSocketAddress(address, port), 500);
    return serverSocket;
}

From source file:org.apache.ftpserver.ssl.MinaImplicitDataChannelTest.java

private void secureClientDataConnection() throws NoSuchAlgorithmException, KeyManagementException {

    // FTPSClient does not support implicit data connections, so we hack it ourselves
    FTPSClient sclient = (FTPSClient) client;
    SSLContext context = SSLContext.getInstance("TLS");

    // these are the same key and trust managers that we initialize the client with
    context.init(new KeyManager[] { clientKeyManager }, new TrustManager[] { clientTrustManager }, null);
    sclient.setSocketFactory(new FTPSSocketFactory(context));
    SSLServerSocketFactory ssf = context.getServerSocketFactory();
    sclient.setServerSocketFactory(ssf);

    // FTPClient should not use SSL secured sockets for the data connection 
}