Example usage for javax.net.ssl SSLContext getProtocol

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

Introduction

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

Prototype

public final String getProtocol() 

Source Link

Document

Returns the protocol name of this SSLContext object.

Usage

From source file:com.twinsoft.convertigo.engine.MySSLSocketFactory.java

private SSLContext createEasySSLContext()
        throws NoSuchProviderException, NoSuchAlgorithmException, KeyManagementException,
        UnrecoverableKeyException, KeyStoreException, CertificateException, IOException {
    Engine.logCertificateManager.debug("(MySSLSocketFactory) Creating SSL context");

    String algorithm = KeyManagerFactory.getDefaultAlgorithm();
    Engine.logCertificateManager.debug("(MySSLSocketFactory) Using KeyManager algorithm " + algorithm);

    KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);

    String keyStoreType = keyStore.endsWith(".pkcs11") ? "pkcs11" : "pkcs12";
    Engine.logCertificateManager.debug("(MySSLSocketFactory) Key store type: " + keyStoreType);

    String alias = null;//from www.  j  a  v a  2 s.com
    KeyStore ks, ts;
    char[] passPhrase;

    if (keyStore.equals("") || (keyStore.endsWith(".udv"))) {
        ks = KeyStore.getInstance(keyStoreType);
        ks.load(null, keyStorePassword.toCharArray());
        kmf.init(ks, null);
    } else {
        File file = new File(keyStore);

        Properties properties = new Properties();
        properties.load(
                new FileInputStream(Engine.CERTIFICATES_PATH + CertificateManager.STORES_PROPERTIES_FILE_NAME));
        String p = properties.getProperty(file.getName(), "");
        int i = p.indexOf('/');
        if (i != -1) {
            alias = p.substring(i + 1);
        }

        if (keyStoreType.equals("pkcs11")) {
            String providerName = file.getName();
            providerName = "SunPKCS11-" + providerName.substring(0, providerName.lastIndexOf('.'));
            Engine.logCertificateManager.debug("(MySSLSocketFactory) Provider name: '" + providerName + "'");

            String pinCode;
            if (i == -1) {
                pinCode = Crypto2.decodeFromHexString(p);
            } else {
                pinCode = Crypto2.decodeFromHexString(p.substring(0, i));
            }

            Engine.logCertificateManager.debug("(MySSLSocketFactory) PIN code: " + pinCode);

            ks = KeyStore.getInstance("pkcs11", providerName);
            ks.load((InputStream) null, pinCode.toCharArray());
            kmf.init(ks, null);
        } else {
            ks = KeyStore.getInstance(keyStoreType);
            passPhrase = keyStorePassword.toCharArray();
            ks.load(new FileInputStream(keyStore), passPhrase);
            kmf.init(ks, passPhrase);
        }
    }
    Engine.logCertificateManager.debug("(MySSLSocketFactory) Client alias: "
            + (alias == null ? "<to be chosen by the security implementor>" : alias));

    ts = KeyStore.getInstance("jks");
    passPhrase = trustStorePassword.toCharArray();
    if (trustStore.equals(""))
        ts.load(null, passPhrase);
    else
        ts.load(new FileInputStream(trustStore), passPhrase);

    algorithm = TrustManagerFactory.getDefaultAlgorithm();
    Engine.logCertificateManager.debug("(MySSLSocketFactory) Using TrustManager algorithm " + algorithm);

    TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm);
    tmf.init(ts);

    TrustManager[] tm = { TRUST_MANAGER };

    MyX509KeyManager xkm = new MyX509KeyManager((X509KeyManager) kmf.getKeyManagers()[0], ks, ts, alias);

    Engine.logCertificateManager
            .debug("(MySSLSocketFactory) trusting all certificates : " + trustAllServerCertificates);

    //SSLContext context = SSLContext.getInstance("SSLv3");
    SSLContext context = SSLContext.getInstance("TLS");
    if (trustAllServerCertificates)
        context.init(new KeyManager[] { xkm }, tm, null);
    else
        context.init(new KeyManager[] { xkm }, tmf.getTrustManagers(), null);

    Engine.logCertificateManager.debug("(MySSLSocketFactory) SSL context created: " + context.getProtocol());
    return context;
}

From source file:net.timewalker.ffmq4.listeners.tcp.io.TcpListener.java

private SSLContext createSSLContext() throws JMSException {
    try {//www . j a va2 s .  co  m
        String sslProtocol = settings.getStringProperty(FFMQCoreSettings.TRANSPORT_TCP_SSL_PROTOCOL, "SSLv3");
        String keyManagerAlgorithm = settings
                .getStringProperty(FFMQCoreSettings.TRANSPORT_TCP_SSL_KEYMANAGER_ALGORITHM, "SunX509");
        String keyStoreType = settings.getStringProperty(FFMQCoreSettings.TRANSPORT_TCP_SSL_KEYSTORE_TYPE,
                "JKS");
        String keyStorePath = settings.getStringProperty(FFMQCoreSettings.TRANSPORT_TCP_SSL_KEYSTORE_PATH,
                "../conf/server-keystore.jks");
        String keyStorePass = settings.getStringProperty(FFMQCoreSettings.TRANSPORT_TCP_SSL_KEYSTORE_PASWORD,
                "ffmqpass");
        String keyPass = settings.getStringProperty(FFMQCoreSettings.TRANSPORT_TCP_SSL_KEYSTORE_KEY_PASSWORD,
                "ffmqpass");

        SSLContext sslContext = SSLContext.getInstance(sslProtocol);
        log.debug("Created an SSL context : protocol=[" + sslContext.getProtocol() + "] provider=["
                + sslContext.getProvider() + "]");

        // Load available keys
        KeyManager[] keyManagers;
        File keyStoreFile = new File(keyStorePath);
        if (!keyStoreFile.canRead())
            throw new FFMQException("Cannot read keystore file : " + keyStoreFile.getAbsolutePath(),
                    "FS_ERROR");

        KeyStore ks = KeyStore.getInstance(keyStoreType);
        log.debug("Created keystore : type=[" + ks.getType() + "] provider=[" + ks.getProvider() + "]");
        char ksPass[] = keyStorePass.toCharArray();
        char ctPass[] = keyPass.toCharArray();
        log.debug("Loading keystore from " + keyStoreFile.getAbsolutePath());
        InputStream kis = new FileInputStream(keyStoreFile);
        ks.load(kis, ksPass);
        kis.close();

        KeyManagerFactory kmf = KeyManagerFactory.getInstance(keyManagerAlgorithm);
        log.debug("Created KeyManagerFactory : algorithm=[" + kmf.getAlgorithm() + "] provider=["
                + kmf.getProvider() + "]");
        log.debug("Initializing KeyManagerFactory with keystore ...");
        kmf.init(ks, ctPass);

        keyManagers = kmf.getKeyManagers();

        sslContext.init(keyManagers, null, null);

        return sslContext;
    } catch (JMSException e) {
        throw e;
    } catch (Exception e) {
        throw new FFMQException("Cannot create SSL context", "NETWORK_ERROR", e);
    }
}

From source file:net.timewalker.ffmq4.transport.tcp.io.TcpPacketTransport.java

private SSLContext createSSLContext() throws JMSException {
    try {/*from w  ww  .j  a va  2 s.  com*/
        String sslProtocol = settings.getStringProperty(FFMQClientSettings.TRANSPORT_TCP_SSL_PROTOCOL, "SSLv3");
        boolean ignoreCertificates = settings
                .getBooleanProperty(FFMQClientSettings.TRANSPORT_TCP_SSL_IGNORE_CERTS, false);

        SSLContext sslContext = SSLContext.getInstance(sslProtocol);
        log.debug("#" + id + " created an SSL context : protocol=[" + sslContext.getProtocol() + "] provider=["
                + sslContext.getProvider() + "]");

        // Load available keys
        KeyManager[] keyManagers = null;
        TrustManager[] trustManagers = null;

        if (ignoreCertificates)
            trustManagers = new TrustManager[] { new PermissiveTrustManager() };

        sslContext.init(keyManagers, trustManagers, null);

        return sslContext;
    } catch (Exception e) {
        throw new FFMQException("Cannot create SSL context", "TRANSPORT_ERROR", e);
    }
}

From source file:org.apache.nifi.processors.standard.PostHTTP.java

private Config getConfig(final String url, final ProcessContext context) {
    final String baseUrl = getBaseUrl(url);
    Config config = configMap.get(baseUrl);
    if (config != null) {
        return config;
    }/*  w  ww. jav  a2 s . c  om*/

    final PoolingHttpClientConnectionManager conMan;
    final SSLContextService sslContextService = context.getProperty(SSL_CONTEXT_SERVICE)
            .asControllerService(SSLContextService.class);
    if (sslContextService == null) {
        conMan = new PoolingHttpClientConnectionManager();
    } else {
        final SSLContext sslContext;
        try {
            sslContext = createSSLContext(sslContextService);
            getLogger().info("PostHTTP supports protocol: " + sslContext.getProtocol());
        } catch (final Exception e) {
            throw new ProcessException(e);
        }

        final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
        // Also use a plain socket factory for regular http connections (especially proxies)
        final Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                .<ConnectionSocketFactory>create().register("https", sslsf)
                .register("http", PlainConnectionSocketFactory.getSocketFactory()).build();

        conMan = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    }

    conMan.setDefaultMaxPerRoute(context.getMaxConcurrentTasks());
    conMan.setMaxTotal(context.getMaxConcurrentTasks());
    config = new Config(conMan);
    final Config existingConfig = configMap.putIfAbsent(baseUrl, config);

    return existingConfig == null ? config : existingConfig;
}

From source file:org.syncany.operations.gui.GuiWebSocketClient.java

private void connect(final DaemonConfigTO daemonConfig, final UserTO daemonUser) throws Exception {
    logger.log(Level.INFO, "Starting GUI websocket client with user " + daemonUser.getUsername() + " at "
            + daemonConfig.getWebServer().getBindAddress() + " ...");

    SSLContext sslContext = UserConfig.createUserSSLContext();
    Xnio xnio = Xnio.getInstance(this.getClass().getClassLoader());
    Pool<ByteBuffer> buffer = new ByteBufferSlicePool(BufferAllocator.BYTE_BUFFER_ALLOCATOR, 1024, 1024);

    OptionMap workerOptions = OptionMap.builder().set(Options.WORKER_IO_THREADS, 2)
            .set(Options.WORKER_TASK_CORE_THREADS, 30).set(Options.WORKER_TASK_MAX_THREADS, 30)
            .set(Options.SSL_PROTOCOL, sslContext.getProtocol())
            .set(Options.SSL_PROVIDER, sslContext.getProvider().getName()).set(Options.TCP_NODELAY, true)
            .set(Options.CORK, true).getMap();

    XnioWorker worker = xnio.createWorker(workerOptions);
    XnioSsl xnioSsl = new JsseXnioSsl(xnio, OptionMap.create(Options.USE_DIRECT_BUFFERS, true), sslContext);
    URI uri = new URI(PROTOCOL + daemonConfig.getWebServer().getBindAddress() + ":"
            + daemonConfig.getWebServer().getBindPort() + ENDPOINT);

    WebSocketClientNegotiation clientNegotiation = new WebSocketClientNegotiation(new ArrayList<String>(),
            new ArrayList<WebSocketExtension>()) {
        @Override/*  w w  w .  j av a2s.  c  om*/
        public void beforeRequest(Map<String, String> headers) {
            String basicAuthPlainUserPass = daemonUser.getUsername() + ":" + daemonUser.getPassword();
            String basicAuthEncodedUserPass = Base64
                    .encodeBase64String(StringUtil.toBytesUTF8(basicAuthPlainUserPass));

            headers.put("Authorization", "Basic " + basicAuthEncodedUserPass);
        }
    };

    webSocketChannel = WebSocketClient
            .connect(worker, xnioSsl, buffer, workerOptions, uri, WebSocketVersion.V13, clientNegotiation)
            .get();

    webSocketChannel.getReceiveSetter().set(new AbstractReceiveListener() {
        @Override
        protected void onFullTextMessage(WebSocketChannel channel, BufferedTextMessage textMessage)
                throws IOException {
            String messageStr = textMessage.getData();
            Message message;

            try {
                logger.log(Level.INFO, "GUI received message: " + messageStr);

                message = MessageFactory.toMessage(messageStr);
                eventBus.post(message);
            } catch (Exception e) {
                logger.log(Level.WARNING, "Unable to parse message: " + e);
            }
        }

        @Override
        protected void onError(WebSocketChannel channel, Throwable error) {
            logger.log(Level.WARNING, "Error: " + error.getMessage());
            waitAndReconnect();
        }
    });

    webSocketChannel.resumeReceives();
}