Example usage for javax.net.ssl TrustManagerFactory getTrustManagers

List of usage examples for javax.net.ssl TrustManagerFactory getTrustManagers

Introduction

In this page you can find the example usage for javax.net.ssl TrustManagerFactory getTrustManagers.

Prototype

public final TrustManager[] getTrustManagers() 

Source Link

Document

Returns one trust manager for each type of trust material.

Usage

From source file:com.ebridgevas.android.ebridgeapp.messaging.mqttservice.MqttAndroidClient.java

/**
 * Get the SSLSocketFactory using SSL key store and password
 * <p>//from  w w  w .ja v a 2 s .co m
 * A convenience method, which will help user to create a SSLSocketFactory
 * object
 * </p>
 * 
 * @param keyStore
 *            the SSL key store which is generated by some SSL key tool,
 *            such as keytool in Java JDK
 * @param password
 *            the password of the key store which is set when the key store
 *            is generated
 * @return SSLSocketFactory used to connect to the server with SSL
 *         authentication
 * @throws MqttSecurityException
 *             if there was any error when getting the SSLSocketFactory
 */
public SSLSocketFactory getSSLSocketFactory(InputStream keyStore, String password)
        throws MqttSecurityException {
    try {
        SSLContext ctx = null;
        SSLSocketFactory sslSockFactory = null;
        KeyStore ts;
        ts = KeyStore.getInstance("BKS");
        ts.load(keyStore, password.toCharArray());
        TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
        tmf.init(ts);
        TrustManager[] tm = tmf.getTrustManagers();
        ctx = SSLContext.getInstance("TLSv1");
        ctx.init(null, tm, null);

        sslSockFactory = ctx.getSocketFactory();
        return sslSockFactory;

    } catch (KeyStoreException e) {
        throw new MqttSecurityException(e);
    } catch (CertificateException e) {
        throw new MqttSecurityException(e);
    } catch (FileNotFoundException e) {
        throw new MqttSecurityException(e);
    } catch (IOException e) {
        throw new MqttSecurityException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new MqttSecurityException(e);
    } catch (KeyManagementException e) {
        throw new MqttSecurityException(e);
    }
}

From source file:com.wwpass.connection.WWPassConnection.java

public WWPassConnection(X509Certificate cert, PKCS8EncodedKeySpec key, int timeoutSec, String spfeAddr)
        throws IOException, GeneralSecurityException {
    timeoutMs = timeoutSec * 1000;//from ww w. j  a v  a 2  s  .  c om
    SpfeURL = "https://" + spfeAddr + "/";
    // Setting up client certificate and key

    X509Certificate[] chain = { cert };

    KeyFactory kf = KeyFactory.getInstance("RSA");
    PrivateKey privKey = kf.generatePrivate(key);

    KeyStore.PrivateKeyEntry pke = new KeyStore.PrivateKeyEntry(privKey, chain);

    //This adds no security but Java requires to password-protect the key
    byte[] password_bytes = new byte[16];
    (new java.security.SecureRandom()).nextBytes(password_bytes);
    // String password = (new BASE64Encoder()).encode(password_bytes);
    String password = (new Base64()).encodeToString(password_bytes);

    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    keyStore.load(null);

    keyStore.setEntry("WWPass client key", pke, new KeyStore.PasswordProtection(password.toCharArray()));
    keyManagerFactory.init(keyStore, password.toCharArray());

    SPFEContext = SSLContext.getInstance("TLS");

    // Making rootCA certificate
    InputStream is = null;
    CertificateFactory cf;
    X509Certificate rootCA = null;
    try {
        is = new ByteArrayInputStream(WWPassCA_DER);
        cf = CertificateFactory.getInstance("X.509");
        rootCA = (X509Certificate) cf.generateCertificate(is);
    } finally {
        if (is != null) {
            is.close();
        }
    }

    //Creating TrustManager for this CA
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());

    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null);
    ks.setCertificateEntry("WWPass Root CA", rootCA);

    trustManagerFactory.init(ks);

    SPFEContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(),
            new java.security.SecureRandom());
}

From source file:com.vmware.photon.controller.deployer.xenon.workflow.BatchCreateManagementWorkflowService.java

private void generateCertificate(DeploymentService.State deploymentState) {
    if (!deploymentState.oAuthEnabled) {
        sendStageProgressPatch(TaskStage.STARTED, TaskState.SubStage.CREATE_VMS);
        return;/*from  ww w .j ava 2s  .  c o m*/
    }

    List<String> command = new ArrayList<>();
    command.add("./" + GENERATE_CERTIFICATE_SCRIPT_NAME);
    command.add(deploymentState.oAuthServerAddress);
    command.add(deploymentState.oAuthPassword);
    command.add(deploymentState.oAuthTenantName);
    command.add(PhotonControllerXenonHost.KEYSTORE_FILE);
    command.add(PhotonControllerXenonHost.KEYSTORE_PASSWORD);

    DeployerContext deployerContext = HostUtils.getDeployerContext(this);
    File scriptLogFile = new File(deployerContext.getScriptLogDirectory(),
            GENERATE_CERTIFICATE_SCRIPT_NAME + ".log");

    ScriptRunner scriptRunner = new ScriptRunner.Builder(command, deployerContext.getScriptTimeoutSec())
            .directory(deployerContext.getScriptDirectory())
            .redirectOutput(ProcessBuilder.Redirect.to(scriptLogFile)).build();

    ListenableFutureTask<Integer> futureTask = ListenableFutureTask.create(scriptRunner);
    HostUtils.getListeningExecutorService(this).submit(futureTask);

    Futures.addCallback(futureTask, new FutureCallback<Integer>() {
        @Override
        public void onSuccess(@javax.validation.constraints.NotNull Integer result) {
            try {
                if (result != 0) {
                    logScriptErrorAndFail(result, scriptLogFile);
                } else {
                    // Set the inInstaller flag to true which would allow us to override the xenon service client to talk
                    // to the auth enabled newly deployed management plane using https with two way SSL.
                    ((PhotonControllerXenonHost) getHost()).setInInstaller(true);

                    // need to switch the ssl context for the thrift clients to use
                    // the generated certs to be able to talk to the authenticated
                    // agents
                    try {
                        SSLContext sslContext = SSLContext.getInstance(KeyStoreUtils.THRIFT_PROTOCOL);
                        TrustManagerFactory tmf = null;

                        tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
                        KeyStore keyStore = KeyStore.getInstance("JKS");
                        InputStream in = FileUtils
                                .openInputStream(new File(PhotonControllerXenonHost.KEYSTORE_FILE));
                        keyStore.load(in, PhotonControllerXenonHost.KEYSTORE_PASSWORD.toCharArray());
                        tmf.init(keyStore);
                        sslContext.init(null, tmf.getTrustManagers(), null);
                        ((PhotonControllerXenonHost) getHost()).regenerateThriftClients(sslContext);

                        KeyStoreUtils.acceptAllCerts(KeyStoreUtils.THRIFT_PROTOCOL);
                    } catch (Throwable t) {
                        ServiceUtils.logSevere(BatchCreateManagementWorkflowService.this,
                                "Regenerating the SSL Context for thrift failed, ignoring to make tests pass, it fail later");
                        ServiceUtils.logSevere(BatchCreateManagementWorkflowService.this, t);
                    }
                    sendStageProgressPatch(TaskStage.STARTED, TaskState.SubStage.CREATE_VMS);
                }
            } catch (Throwable t) {
                failTask(t);
            }
        }

        @Override
        public void onFailure(Throwable throwable) {
            failTask(throwable);
        }
    });
}

From source file:net.java.sip.communicator.impl.certificate.CertificateServiceImpl.java

public X509TrustManager getTrustManager(final Iterable<String> identitiesToTest,
        final CertificateMatcher clientVerifier, final CertificateMatcher serverVerifier)
        throws GeneralSecurityException {
    // obtain the default X509 trust manager
    X509TrustManager defaultTm = null;
    TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());

    //workaround for https://bugs.openjdk.java.net/browse/JDK-6672015
    KeyStore ks = null;//  w  ww.  j  av a 2 s  .  co m
    String tsType = System.getProperty("javax.net.ssl.trustStoreType", null);
    if ("Windows-ROOT".equals(tsType)) {
        try {
            ks = KeyStore.getInstance(tsType);
            ks.load(null, null);
            int numEntries = keyStoreAppendIndex(ks);
            logger.info(
                    "Using Windows-ROOT. Aliases sucessfully renamed on " + numEntries + " root certificates.");
        } catch (Exception e) {
            logger.error("Could not rename Windows-ROOT aliases", e);
        }
    }

    tmFactory.init(ks);
    for (TrustManager m : tmFactory.getTrustManagers()) {
        if (m instanceof X509TrustManager) {
            defaultTm = (X509TrustManager) m;
            break;
        }
    }
    if (defaultTm == null)
        throw new GeneralSecurityException("No default X509 trust manager found");

    final X509TrustManager tm = defaultTm;

    return new X509TrustManager() {
        private boolean serverCheck;

        public X509Certificate[] getAcceptedIssuers() {
            return tm.getAcceptedIssuers();
        }

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

        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            serverCheck = false;
            checkCertTrusted(chain, authType);
        }

        private void checkCertTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // check and default configurations for property
            // if missing default is null - false
            String defaultAlwaysTrustMode = CertificateVerificationActivator.getResources()
                    .getSettingsString(CertificateService.PNAME_ALWAYS_TRUST);

            if (config.getBoolean(PNAME_ALWAYS_TRUST, Boolean.parseBoolean(defaultAlwaysTrustMode)))
                return;

            try {
                // check the certificate itself (issuer, validity)
                try {
                    chain = tryBuildChain(chain);
                } catch (Exception e) {
                } // don't care and take the chain as is

                if (serverCheck)
                    tm.checkServerTrusted(chain, authType);
                else
                    tm.checkClientTrusted(chain, authType);

                if (identitiesToTest == null || !identitiesToTest.iterator().hasNext())
                    return;
                else if (serverCheck)
                    serverVerifier.verify(identitiesToTest, chain[0]);
                else
                    clientVerifier.verify(identitiesToTest, chain[0]);

                // ok, globally valid cert
            } catch (CertificateException e) {
                String thumbprint = getThumbprint(chain[0], THUMBPRINT_HASH_ALGORITHM);
                String message = null;
                List<String> propNames = new LinkedList<String>();
                List<String> storedCerts = new LinkedList<String>();
                String appName = R.getSettingsString("service.gui.APPLICATION_NAME");

                if (identitiesToTest == null || !identitiesToTest.iterator().hasNext()) {
                    String propName = PNAME_CERT_TRUST_PREFIX + ".server." + thumbprint;
                    propNames.add(propName);

                    message = R.getI18NString("service.gui." + "CERT_DIALOG_DESCRIPTION_TXT_NOHOST",
                            new String[] { appName });

                    // get the thumbprints from the permanent allowances
                    String hashes = config.getString(propName);
                    if (hashes != null)
                        for (String h : hashes.split(","))
                            storedCerts.add(h);

                    // get the thumbprints from the session allowances
                    List<String> sessionCerts = sessionAllowedCertificates.get(propName);
                    if (sessionCerts != null)
                        storedCerts.addAll(sessionCerts);
                } else {
                    if (serverCheck) {
                        message = R.getI18NString("service.gui." + "CERT_DIALOG_DESCRIPTION_TXT",
                                new String[] { appName, identitiesToTest.toString() });
                    } else {
                        message = R.getI18NString("service.gui." + "CERT_DIALOG_PEER_DESCRIPTION_TXT",
                                new String[] { appName, identitiesToTest.toString() });
                    }
                    for (String identity : identitiesToTest) {
                        String propName = PNAME_CERT_TRUST_PREFIX + ".param." + identity;
                        propNames.add(propName);

                        // get the thumbprints from the permanent allowances
                        String hashes = config.getString(propName);
                        if (hashes != null)
                            for (String h : hashes.split(","))
                                storedCerts.add(h);

                        // get the thumbprints from the session allowances
                        List<String> sessionCerts = sessionAllowedCertificates.get(propName);
                        if (sessionCerts != null)
                            storedCerts.addAll(sessionCerts);
                    }
                }

                if (!storedCerts.contains(thumbprint)) {
                    switch (verify(chain, message)) {
                    case DO_NOT_TRUST:
                        logger.info("Untrusted certificate", e);
                        throw new CertificateException("The peer provided certificate with Subject <"
                                + chain[0].getSubjectDN() + "> is not trusted", e);
                    case TRUST_ALWAYS:
                        for (String propName : propNames) {
                            String current = config.getString(propName);
                            String newValue = thumbprint;
                            if (current != null)
                                newValue += "," + current;
                            config.setProperty(propName, newValue);
                        }
                        break;
                    case TRUST_THIS_SESSION_ONLY:
                        for (String propName : propNames)
                            getSessionCertEntry(propName).add(thumbprint);
                        break;
                    }
                }
                // ok, we've seen this certificate before
            }
        }

        private X509Certificate[] tryBuildChain(X509Certificate[] chain)
                throws IOException, URISyntaxException, CertificateException {
            // Only try to build chains for servers that send only their
            // own cert, but no issuer. This also matches self signed (will
            // be ignored later) and Root-CA signed certs. In this case we
            // throw the Root-CA away after the lookup
            if (chain.length != 1)
                return chain;

            // ignore self signed certs
            if (chain[0].getIssuerDN().equals(chain[0].getSubjectDN()))
                return chain;

            // prepare for the newly created chain
            List<X509Certificate> newChain = new ArrayList<X509Certificate>(chain.length + 4);
            for (X509Certificate cert : chain) {
                newChain.add(cert);
            }

            // search from the topmost certificate upwards
            CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
            X509Certificate current = chain[chain.length - 1];
            boolean foundParent;
            int chainLookupCount = 0;
            do {
                foundParent = false;
                // extract the url(s) where the parent certificate can be
                // found
                byte[] aiaBytes = current.getExtensionValue(Extension.authorityInfoAccess.getId());
                if (aiaBytes == null)
                    break;

                AuthorityInformationAccess aia = AuthorityInformationAccess
                        .getInstance(X509ExtensionUtil.fromExtensionValue(aiaBytes));

                // the AIA may contain different URLs and types, try all
                // of them
                for (AccessDescription ad : aia.getAccessDescriptions()) {
                    // we are only interested in the issuer certificate,
                    // not in OCSP urls the like
                    if (!ad.getAccessMethod().equals(AccessDescription.id_ad_caIssuers))
                        continue;

                    GeneralName gn = ad.getAccessLocation();
                    if (!(gn.getTagNo() == GeneralName.uniformResourceIdentifier
                            && gn.getName() instanceof DERIA5String))
                        continue;

                    URI uri = new URI(((DERIA5String) gn.getName()).getString());
                    // only http(s) urls; LDAP is taken care of in the
                    // default implementation
                    if (!(uri.getScheme().equalsIgnoreCase("http") || uri.getScheme().equals("https")))
                        continue;

                    X509Certificate cert = null;

                    // try to get cert from cache first to avoid consecutive
                    // (slow) http lookups
                    AiaCacheEntry cache = aiaCache.get(uri);
                    if (cache != null && cache.cacheDate.after(new Date())) {
                        cert = cache.cert;
                    } else {
                        // download if no cache entry or if it is expired
                        if (logger.isDebugEnabled())
                            logger.debug("Downloading parent certificate for <" + current.getSubjectDN()
                                    + "> from <" + uri + ">");
                        try {
                            InputStream is = HttpUtils.openURLConnection(uri.toString()).getContent();
                            cert = (X509Certificate) certFactory.generateCertificate(is);
                        } catch (Exception e) {
                            logger.debug("Could not download from <" + uri + ">");
                        }
                        // cache for 10mins
                        aiaCache.put(uri,
                                new AiaCacheEntry(new Date(new Date().getTime() + 10 * 60 * 1000), cert));
                    }
                    if (cert != null) {
                        if (!cert.getIssuerDN().equals(cert.getSubjectDN())) {
                            newChain.add(cert);
                            foundParent = true;
                            current = cert;
                            break; // an AD was valid, ignore others
                        } else
                            logger.debug("Parent is self-signed, ignoring");
                    }
                }
                chainLookupCount++;
            } while (foundParent && chainLookupCount < 10);
            chain = newChain.toArray(chain);
            return chain;
        }
    };
}

From source file:net.myrrix.client.ClientRecommender.java

private SSLSocketFactory buildSSLSocketFactory() throws IOException {

    final HostnameVerifier defaultVerifier = HttpsURLConnection.getDefaultHostnameVerifier();
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
        @Override/*  w w w .  j a  v a2 s  .  c o m*/
        public boolean verify(String hostname, SSLSession sslSession) {
            return ignoreHTTPSHost || "localhost".equals(hostname) || "127.0.0.1".equals(hostname)
                    || defaultVerifier.verify(hostname, sslSession);
        }
    });

    try {

        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        File trustStoreFile = config.getKeystoreFile().getAbsoluteFile();
        String password = config.getKeystorePassword();
        Preconditions.checkNotNull(password);

        InputStream in = new FileInputStream(trustStoreFile);
        try {
            keyStore.load(in, password.toCharArray());
        } finally {
            in.close();
        }

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(keyStore);

        SSLContext ctx;
        try {
            ctx = SSLContext.getInstance("TLSv1.1"); // Java 7 only
        } catch (NoSuchAlgorithmException ignored) {
            log.info("TLSv1.1 unavailable, falling back to TLSv1");
            ctx = SSLContext.getInstance("TLSv1"); // Java 6       
            // This also seems to be necessary:
            if (System.getProperty("https.protocols") == null) {
                System.setProperty("https.protocols", "TLSv1");
            }
        }
        ctx.init(null, tmf.getTrustManagers(), null);
        return ctx.getSocketFactory();

    } catch (NoSuchAlgorithmException nsae) {
        // can't happen?
        throw new IllegalStateException(nsae);
    } catch (KeyStoreException kse) {
        throw new IOException(kse);
    } catch (KeyManagementException kme) {
        throw new IOException(kme);
    } catch (CertificateException ce) {
        throw new IOException(ce);
    }
}

From source file:org.lockss.protocol.BlockingStreamComm.java

/** One-time startup configuration  */
private void configure(Configuration config, Configuration prevConfig, Configuration.Differences changedKeys) {
    enabled = config.getBoolean(PARAM_ENABLED, DEFAULT_ENABLED);
    if (!enabled) {
        return;//w ww .j  a  v a2s .com
    }
    paramMinPoolSize = config.getInt(PARAM_CHANNEL_THREAD_POOL_MIN, DEFAULT_CHANNEL_THREAD_POOL_MIN);
    paramMaxPoolSize = config.getInt(PARAM_CHANNEL_THREAD_POOL_MAX, DEFAULT_CHANNEL_THREAD_POOL_MAX);
    paramPoolKeepaliveTime = config.getTimeInterval(PARAM_CHANNEL_THREAD_POOL_KEEPALIVE,
            DEFAULT_CHANNEL_THREAD_POOL_KEEPALIVE);

    if (config.getBoolean(PARAM_BIND_TO_LOCAL_IP_ONLY, DEFAULT_BIND_TO_LOCAL_IP_ONLY)) {
        bindAddr = config.get(IdentityManager.PARAM_LOCAL_IP);
    }
    sendFromBindAddr = config.getBoolean(PARAM_SEND_FROM_BIND_ADDR, DEFAULT_SEND_FROM_BIND_ADDR);

    if (changedKeys.contains(PARAM_USE_V3_OVER_SSL)) {
        paramUseV3OverSsl = config.getBoolean(PARAM_USE_V3_OVER_SSL, DEFAULT_USE_V3_OVER_SSL);
        sockFact = null;
        // XXX shut down old listen socket, do exponential backoff
        // XXX on bind() to bring up new listen socket
        // XXX then move this to the "change on the fly" above
    }
    if (!paramUseV3OverSsl)
        return;
    log.info("Using SSL");
    // We're trying to use SSL
    if (changedKeys.contains(PARAM_USE_SSL_CLIENT_AUTH)) {
        paramSslClientAuth = config.getBoolean(PARAM_USE_SSL_CLIENT_AUTH, DEFAULT_USE_SSL_CLIENT_AUTH);
        sockFact = null;
    }
    if (sslServerSocketFactory != null && sslSocketFactory != null) {
        // already initialized
        return;
    }

    if (changedKeys.contains(PARAM_SSL_KEYSTORE_NAME) || changedKeys.contains(PARAM_SSL_PRIVATE_KEYSTORE_NAME)
            || changedKeys.contains(PARAM_SSL_PUBLIC_KEYSTORE_NAME)) {
        String name = getOrNull(config, PARAM_SSL_KEYSTORE_NAME);
        String priv = getOrNull(config, PARAM_SSL_PRIVATE_KEYSTORE_NAME);
        String pub = getOrNull(config, PARAM_SSL_PUBLIC_KEYSTORE_NAME);
        if (!StringUtil.isNullString(name)) {
            paramSslPrivateKeyStoreName = name;
            paramSslPublicKeyStoreName = name;
        }
        if (priv != null) {
            if (name != null && !priv.equals(name)) {
                log.warning("Overriding " + PARAM_SSL_KEYSTORE_NAME + ": " + name + " with "
                        + PARAM_SSL_PRIVATE_KEYSTORE_NAME + ": " + priv);
            }
            paramSslPrivateKeyStoreName = priv;
        }
        if (pub != null) {
            if (name != null && !pub.equals(name)) {
                log.warning("Overriding " + PARAM_SSL_KEYSTORE_NAME + ": " + name + " with "
                        + PARAM_SSL_PUBLIC_KEYSTORE_NAME + ": " + pub);
            }
            paramSslPublicKeyStoreName = pub;
        }
        if (StringUtil.equalStrings(paramSslPublicKeyStoreName, paramSslPrivateKeyStoreName)) {
            // so can use == later
            paramSslPrivateKeyStoreName = paramSslPublicKeyStoreName;
            log.debug("Using keystore " + paramSslPrivateKeyStoreName);
        } else {
            log.debug("Using private keystore " + paramSslPrivateKeyStoreName + ", public keystore "
                    + paramSslPublicKeyStoreName);
        }
        sockFact = null;
    }
    if (changedKeys.contains(PARAM_SSL_PROTOCOL)) {
        paramSslProtocol = config.get(PARAM_SSL_PROTOCOL, DEFAULT_SSL_PROTOCOL);
        sockFact = null;
    }
    KeyManagerFactory kmf = keystoreMgr.getKeyManagerFactory(paramSslPrivateKeyStoreName, "LCAP");
    if (kmf == null) {
        throw new IllegalArgumentException("Keystore not found: " + paramSslPrivateKeyStoreName);
    }
    KeyManager[] kma = kmf.getKeyManagers();

    TrustManagerFactory tmf = keystoreMgr.getTrustManagerFactory(paramSslPublicKeyStoreName, "LCAP");
    if (tmf == null) {
        throw new IllegalArgumentException("Keystore not found: " + paramSslPublicKeyStoreName);
    }
    TrustManager[] tma = tmf.getTrustManagers();

    // Now create an SSLContext from the KeyManager
    SSLContext sslContext = null;
    try {
        RandomManager rmgr = getDaemon().getRandomManager();
        SecureRandom rng = rmgr.getSecureRandom();

        sslContext = SSLContext.getInstance(paramSslProtocol);
        sslContext.init(kma, tma, rng);
        // Now create the SSL socket factories from the context
        sslServerSocketFactory = sslContext.getServerSocketFactory();
        sslSocketFactory = sslContext.getSocketFactory();
        log.info("SSL init successful");
    } catch (NoSuchAlgorithmException ex) {
        log.error("Creating SSL context threw " + ex);
        sslContext = null;
    } catch (NoSuchProviderException ex) {
        log.error("Creating SSL context threw " + ex);
        sslContext = null;
    } catch (KeyManagementException ex) {
        log.error("Creating SSL context threw " + ex);
        sslContext = null;
    }
}

From source file:org.apache.hive.jdbc.HiveConnection.java

SSLConnectionSocketFactory getTwoWaySSLSocketFactory() throws SQLException {
    SSLConnectionSocketFactory socketFactory = null;

    try {/*from  ww w  .jav  a2s  .c  o  m*/
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(
                JdbcConnectionParams.SUNX509_ALGORITHM_STRING, JdbcConnectionParams.SUNJSSE_ALGORITHM_STRING);
        String keyStorePath = sessConfMap.get(JdbcConnectionParams.SSL_KEY_STORE);
        String keyStorePassword = sessConfMap.get(JdbcConnectionParams.SSL_KEY_STORE_PASSWORD);
        KeyStore sslKeyStore = KeyStore.getInstance(JdbcConnectionParams.SSL_KEY_STORE_TYPE);

        if (keyStorePath == null || keyStorePath.isEmpty()) {
            throw new IllegalArgumentException(JdbcConnectionParams.SSL_KEY_STORE
                    + " Not configured for 2 way SSL connection, keyStorePath param is empty");
        }
        try (FileInputStream fis = new FileInputStream(keyStorePath)) {
            sslKeyStore.load(fis, keyStorePassword.toCharArray());
        }
        keyManagerFactory.init(sslKeyStore, keyStorePassword.toCharArray());

        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(JdbcConnectionParams.SUNX509_ALGORITHM_STRING);
        String trustStorePath = sessConfMap.get(JdbcConnectionParams.SSL_TRUST_STORE);
        String trustStorePassword = sessConfMap.get(JdbcConnectionParams.SSL_TRUST_STORE_PASSWORD);
        KeyStore sslTrustStore = KeyStore.getInstance(JdbcConnectionParams.SSL_TRUST_STORE_TYPE);

        if (trustStorePath == null || trustStorePath.isEmpty()) {
            throw new IllegalArgumentException(
                    JdbcConnectionParams.SSL_TRUST_STORE + " Not configured for 2 way SSL connection");
        }
        try (FileInputStream fis = new FileInputStream(trustStorePath)) {
            sslTrustStore.load(fis, trustStorePassword.toCharArray());
        }
        trustManagerFactory.init(sslTrustStore);
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(),
                new SecureRandom());
        socketFactory = new SSLConnectionSocketFactory(context);
    } catch (Exception e) {
        throw new SQLException("Error while initializing 2 way ssl socket factory ", e);
    }
    return socketFactory;
}

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 www  .  j  a  va2  s. co 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.ejbca.core.protocol.ws.CommonEjbcaWS.java

/** Getting SSL socket factory using the Admin cert created for client certificate authentication **/
private SSLSocketFactory getSSLFactory() throws IOException, NoSuchAlgorithmException,
        UnrecoverableKeyException, KeyStoreException, CertificateException, KeyManagementException {
    // Put the key and certs in the user keystore (if available)
    java.security.KeyStore ks = java.security.KeyStore.getInstance("jks");
    ks.load(new FileInputStream(TEST_ADMIN_FILE), PASSWORD.toCharArray());
    final KeyManagerFactory kmf;
    kmf = KeyManagerFactory.getInstance("SunX509");
    kmf.init(ks, PASSWORD.toCharArray());
    final KeyManager km[] = kmf.getKeyManagers();

    final TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
    tmf.init(ks);//from   www .ja  v  a  2s. c o  m
    final TrustManager tm[] = tmf.getTrustManagers();
    if (km == null && tm == null) {
        return (SSLSocketFactory) SSLSocketFactory.getDefault();
    }
    final SSLContext ctx = SSLContext.getInstance("TLS");
    ctx.init(km, tm, null);
    return ctx.getSocketFactory();
}

From source file:com.irccloud.android.NetworkConnection.java

@SuppressWarnings("deprecation")
public NetworkConnection() {
    String version;/*from   w  w  w .java2  s  .  c o m*/
    String network_type = null;
    try {
        version = "/" + IRCCloudApplication.getInstance().getPackageManager().getPackageInfo(
                IRCCloudApplication.getInstance().getApplicationContext().getPackageName(), 0).versionName;
    } catch (Exception e) {
        version = "";
    }

    try {
        ConnectivityManager cm = (ConnectivityManager) IRCCloudApplication.getInstance()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        if (ni != null)
            network_type = ni.getTypeName();
    } catch (Exception e) {
    }

    try {
        config = new JSONObject(PreferenceManager
                .getDefaultSharedPreferences(IRCCloudApplication.getInstance().getApplicationContext())
                .getString("config", "{}"));
    } catch (JSONException e) {
        e.printStackTrace();
        config = new JSONObject();
    }

    useragent = "IRCCloud" + version + " (" + android.os.Build.MODEL + "; "
            + Locale.getDefault().getCountry().toLowerCase() + "; " + "Android "
            + android.os.Build.VERSION.RELEASE;

    WindowManager wm = (WindowManager) IRCCloudApplication.getInstance()
            .getSystemService(Context.WINDOW_SERVICE);
    useragent += "; " + wm.getDefaultDisplay().getWidth() + "x" + wm.getDefaultDisplay().getHeight();

    if (network_type != null)
        useragent += "; " + network_type;

    useragent += ")";

    WifiManager wfm = (WifiManager) IRCCloudApplication.getInstance().getApplicationContext()
            .getSystemService(Context.WIFI_SERVICE);
    wifiLock = wfm.createWifiLock(TAG);

    kms = new X509ExtendedKeyManager[1];
    kms[0] = new X509ExtendedKeyManager() {
        @Override
        public String chooseClientAlias(String[] keyTypes, Principal[] issuers, Socket socket) {
            return SSLAuthAlias;
        }

        @Override
        public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) {
            throw new UnsupportedOperationException();
        }

        @Override
        public X509Certificate[] getCertificateChain(String alias) {
            return SSLAuthCertificateChain;
        }

        @Override
        public String[] getClientAliases(String keyType, Principal[] issuers) {
            throw new UnsupportedOperationException();
        }

        @Override
        public String[] getServerAliases(String keyType, Principal[] issuers) {
            throw new UnsupportedOperationException();
        }

        @Override
        public PrivateKey getPrivateKey(String alias) {
            return SSLAuthKey;
        }
    };

    tms = new TrustManager[1];
    tms[0] = new X509TrustManager() {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            throw new CertificateException("Not implemented");
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            try {
                TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("X509");
                trustManagerFactory.init((KeyStore) null);

                for (TrustManager trustManager : trustManagerFactory.getTrustManagers()) {
                    if (trustManager instanceof X509TrustManager) {
                        X509TrustManager x509TrustManager = (X509TrustManager) trustManager;
                        x509TrustManager.checkServerTrusted(chain, authType);
                    }
                }
            } catch (KeyStoreException e) {
                throw new CertificateException(e);
            } catch (NoSuchAlgorithmException e) {
                throw new CertificateException(e);
            }

            if (BuildConfig.SSL_FPS != null && BuildConfig.SSL_FPS.length > 0) {
                try {
                    MessageDigest md = MessageDigest.getInstance("SHA-1");
                    byte[] sha1 = md.digest(chain[0].getEncoded());
                    // http://stackoverflow.com/questions/9655181/convert-from-byte-array-to-hex-string-in-java
                    final char[] hexArray = "0123456789ABCDEF".toCharArray();
                    char[] hexChars = new char[sha1.length * 2];
                    for (int j = 0; j < sha1.length; j++) {
                        int v = sha1[j] & 0xFF;
                        hexChars[j * 2] = hexArray[v >>> 4];
                        hexChars[j * 2 + 1] = hexArray[v & 0x0F];
                    }
                    String hexCharsStr = new String(hexChars);
                    boolean matched = false;
                    for (String fp : BuildConfig.SSL_FPS) {
                        if (fp.equals(hexCharsStr)) {
                            matched = true;
                            break;
                        }
                    }
                    if (!matched)
                        throw new CertificateException("Incorrect CN in cert chain");
                } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    };
    WebSocketClient.setTrustManagers(tms);
}