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:orca.ektorp.client.ContextualSSLSocketFactory.java

private static SSLContext createSSLContext(String algorithm, final KeyStore keystore,
        final String keystorePassword, final KeyStore truststore, final SecureRandom random,
        final TrustStrategy trustStrategy)
        throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, KeyManagementException {
    if (algorithm == null) {
        algorithm = TLS;//w ww  . j  av a2  s . c  om
    }
    KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmfactory.init(keystore, keystorePassword != null ? keystorePassword.toCharArray() : null);
    KeyManager[] keymanagers = kmfactory.getKeyManagers();
    TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmfactory.init(truststore);
    TrustManager[] trustmanagers = tmfactory.getTrustManagers();
    if (trustmanagers != null && trustStrategy != null) {
        for (int i = 0; i < trustmanagers.length; i++) {
            TrustManager tm = trustmanagers[i];
            /*
             * @TODO: I need to uncomment the 3 lines below. TrustManagerDecorator is not public (package visibility)
             */
            // if (tm instanceof X509TrustManager) {
            //    trustmanagers[i] = new TrustManagerDecorator(
            //            (X509TrustManager) tm, trustStrategy);
            //}
        }
    }

    SSLContext sslcontext = SSLContext.getInstance(algorithm);
    sslcontext.init(keymanagers, trustmanagers, random);
    return sslcontext;
}

From source file:org.exoplatform.services.videocall.AuthService.java

protected static TrustManager[] getTrustManagers(InputStream trustStoreFile, String trustStorePassword)
        throws Exception {
    CertificateFactory certificateFactory = null;
    try {//from  ww  w. ja v  a  2  s . c o m
        certificateFactory = CertificateFactory.getInstance("X.509");
    } catch (CertificateException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Could not initialize the certificate " + e.getMessage());
        }
    }

    Certificate caCert = null;
    try {
        caCert = certificateFactory.generateCertificate(trustStoreFile);
    } catch (CertificateException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Bad key or certificate in " + trustStoreFile, e.getMessage());
        }
    }

    KeyStore trustStore = null;
    try {
        trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
    } catch (KeyStoreException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Java implementation cannot manipulate " + KeyStore.getDefaultType() + " keystores");
        }
    } catch (NoSuchAlgorithmException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Could not initialize truststore ", e);
        }
    } catch (CertificateException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Could not initialize truststore ", e);
        }
    } catch (IOException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Could not initialize truststore ", e);
        }
    }

    try {
        trustStore.setCertificateEntry("CA", caCert);
    } catch (KeyStoreException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error(trustStoreFile + " cannot be used as a CA", e);
        }
    }

    TrustManagerFactory tmf = null;
    try {
        tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(trustStore);
    } catch (NoSuchAlgorithmException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Java implementation cannot manipulate " + KeyStore.getDefaultType() + " trusts", e);
        }
    } catch (KeyStoreException e) {
        LOG.error("Java implementation cannot manipulate " + KeyStore.getDefaultType() + " trusts", e);
    }
    return tmf.getTrustManagers();
}

From source file:com.jrummyapps.android.safetynet.SafetyNetHelper.java

/**
 * Validate the SafetyNet response using the Android Device Verification API. This API performs a validation check on
 * the JWS message returned from the SafetyNet service.
 *
 * <b>Important:</b> This use of the Android Device Verification API only validates that the provided JWS message was
 * received from the SafetyNet service. It <i>does not</i> verify that the payload data matches your original
 * compatibility check request./*from w  w  w.j a  v a2s  . c  o  m*/
 *
 * @param jws
 *     The output of {@link SafetyNetApi.AttestationResult#getJwsResult()}.
 * @param apiKey
 *     The Android Device Verification API key
 * @return {@code true} if the provided JWS message was received from the SafetyNet service.
 * @throws SafetyNetError
 *     if an error occurs while verifying the JSON Web Signature.
 */
public static boolean validate(@NonNull String jws, @NonNull String apiKey) throws SafetyNetError {
    try {
        URL verifyApiUrl = new URL(GOOGLE_VERIFICATION_URL + apiKey);

        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init((KeyStore) null);
        TrustManager[] defaultTrustManagers = trustManagerFactory.getTrustManagers();
        TrustManager[] trustManagers = Arrays.copyOf(defaultTrustManagers, defaultTrustManagers.length + 1);
        trustManagers[defaultTrustManagers.length] = new GoogleApisTrustManager();

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

        HttpsURLConnection urlConnection = (HttpsURLConnection) verifyApiUrl.openConnection();
        urlConnection.setSSLSocketFactory(sslContext.getSocketFactory());
        urlConnection.setRequestMethod("POST");
        urlConnection.setRequestProperty("Content-Type", "application/json");

        JSONObject requestJson = new JSONObject();
        requestJson.put("signedAttestation", jws);
        byte[] outputInBytes = requestJson.toString().getBytes("UTF-8");
        OutputStream os = urlConnection.getOutputStream();
        os.write(outputInBytes);
        os.close();

        urlConnection.connect();
        InputStream is = urlConnection.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        for (String line = reader.readLine(), nl = ""; line != null; line = reader.readLine(), nl = "\n") {
            sb.append(nl).append(line);
        }

        return new JSONObject(sb.toString()).getBoolean("isValidSignature");
    } catch (Exception e) {
        throw new SafetyNetError(e);
    }
}

From source file:org.apache.cassandra.hadoop.cql3.CqlConfigHelper.java

private static SSLContext getSSLContext(String truststorePath, String truststorePassword, String keystorePath,
        String keystorePassword) throws NoSuchAlgorithmException, KeyStoreException, CertificateException,
        IOException, UnrecoverableKeyException, KeyManagementException {
    SSLContext ctx;/*from  ww w . ja  v  a  2  s. c o  m*/
    try (FileInputStream tsf = new FileInputStream(truststorePath);
            FileInputStream ksf = new FileInputStream(keystorePath)) {
        ctx = SSLContext.getInstance("SSL");

        KeyStore ts = KeyStore.getInstance("JKS");
        ts.load(tsf, truststorePassword.toCharArray());
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ts);

        KeyStore ks = KeyStore.getInstance("JKS");
        ks.load(ksf, keystorePassword.toCharArray());
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(ks, keystorePassword.toCharArray());

        ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());
    }
    return ctx;
}

From source file:org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils.java

/**
 * Initializes the SSL Context/*from  w  ww  .jav a 2 s .co m*/
 */
private static void initSSLConnection()
        throws NoSuchAlgorithmException, UnrecoverableKeyException, KeyStoreException, KeyManagementException {
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KEY_MANAGER_TYPE);
    keyManagerFactory.init(keyStore, keyStorePassword);
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TRUST_MANAGER_TYPE);
    trustManagerFactory.init(trustStore);

    // Create and initialize SSLContext for HTTPS communication
    sslContext = SSLContext.getInstance(SSLV3);
    sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
    SSLContext.setDefault(sslContext);
}

From source file:com.guster.skywebservice.library.webservice.SkyHttp.java

public static void setSSLCertificate(InputStream certificateFile) throws CertificateException, IOException,
        KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    Certificate cert = cf.generateCertificate(certificateFile);

    certificateFile.close();/* www  . ja  va2 s  .  c o  m*/

    // create a keystore containing the certificate
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    keyStore.load(null, null);
    keyStore.setCertificateEntry("ca", cert);

    // create a trust manager for our certificate
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(keyStore);

    // create a SSLContext that uses our trust manager
    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, tmf.getTrustManagers(), null);

    // set socket factory
    setSSLSocketFactory(context.getSocketFactory());
}

From source file:com.wso2.mobile.mdm.utils.ServerUtilities.java

public static HttpsURLConnection getTrustedConnection(Context context, HttpsURLConnection conn) {
    HttpsURLConnection urlConnection = conn;
    try {/* www  . j av a 2 s. c o m*/
        KeyStore localTrustStore;

        localTrustStore = KeyStore.getInstance("BKS");

        InputStream in = context.getResources().openRawResource(R.raw.emm_truststore);

        localTrustStore.load(in, CommonUtilities.TRUSTSTORE_PASSWORD.toCharArray());

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

        tmf.init(localTrustStore);

        SSLContext sslCtx;

        sslCtx = SSLContext.getInstance("TLS");

        sslCtx.init(null, tmf.getTrustManagers(), null);

        urlConnection.setSSLSocketFactory(sslCtx.getSocketFactory());
        return urlConnection;
    } catch (KeyManagementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    } catch (CertificateException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
        return null;
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
        return null;
    } catch (KeyStoreException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
        return null;
    }

}

From source file:org.apache.synapse.config.SynapseConfigUtils.java

/**
 * Helper method to create a HttpSURLConnection with provided KeyStores
 *
 * @param url Https URL//w  w w.jav a 2 s  . co m
 * @param synapseProperties properties for extracting info
 * @param proxy if there is a proxy
 * @return gives out the connection created
 */
private static HttpsURLConnection getHttpsURLConnection(URL url, Properties synapseProperties, Proxy proxy) {

    if (log.isDebugEnabled()) {
        log.debug("Creating a HttpsURL Connection from given URL : " + url);
    }

    KeyManager[] keyManagers = null;
    TrustManager[] trustManagers = null;

    IdentityKeyStoreInformation identityInformation = KeyStoreInformationFactory
            .createIdentityKeyStoreInformation(synapseProperties);

    if (identityInformation != null) {
        KeyManagerFactory keyManagerFactory = identityInformation.getIdentityKeyManagerFactoryInstance();
        if (keyManagerFactory != null) {
            keyManagers = keyManagerFactory.getKeyManagers();
        }

    } else {
        if (log.isDebugEnabled()) {
            log.debug("There is no private key entry store configuration." + " Will use JDK's default one");
        }
    }

    TrustKeyStoreInformation trustInformation = KeyStoreInformationFactory
            .createTrustKeyStoreInformation(synapseProperties);

    if (trustInformation != null) {
        TrustManagerFactory trustManagerFactory = trustInformation.getTrustManagerFactoryInstance();
        if (trustManagerFactory != null) {
            trustManagers = trustManagerFactory.getTrustManagers();
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("There is no trusted certificate store configuration." + " Will use JDK's default one");
        }
    }

    try {
        HttpsURLConnection connection;
        if (proxy != null) {
            connection = (HttpsURLConnection) url.openConnection(proxy);
        } else {
            connection = (HttpsURLConnection) url.openConnection();
        }
        //Create a SSLContext
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagers, trustManagers, null);
        connection.setSSLSocketFactory(sslContext.getSocketFactory());

        if (trustInformation != null) {
            // Determine is it need to overwrite default Host Name verifier
            boolean enableHostnameVerifier = true;
            String value = trustInformation.getParameter(KeyStoreInformation.ENABLE_HOST_NAME_VERIFIER);
            if (value != null) {
                enableHostnameVerifier = Boolean.parseBoolean(value);
            }

            if (!enableHostnameVerifier) {

                if (log.isDebugEnabled()) {
                    log.debug("Overriding default HostName Verifier." + "HostName verification disabled");
                }

                connection.setHostnameVerifier(new javax.net.ssl.HostnameVerifier() {
                    public boolean verify(String hostname, javax.net.ssl.SSLSession session) {
                        if (log.isTraceEnabled()) {
                            log.trace("HostName verification disabled");
                            log.trace("Host:   " + hostname);
                            log.trace("Peer Host:  " + session.getPeerHost());
                        }
                        return true;
                    }
                });
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Using default HostName verifier...");
                }
            }
        }
        return connection;

    } catch (NoSuchAlgorithmException e) {
        handleException("Error loading SSLContext ", e);
    } catch (KeyManagementException e) {
        handleException("Error initiation SSLContext with KeyManagers", e);
    } catch (IOException e) {
        handleException("Error opening a https connection from URL : " + url, e);
    }
    return null;
}

From source file:com.swisscom.safeconnect.backend.SwisscomSslSocketFactory.java

public SwisscomSslSocketFactory(KeyStore truststore)
        throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
    super(truststore);

    String alg = TrustManagerFactory.getDefaultAlgorithm();
    TrustManagerFactory tmFact = TrustManagerFactory.getInstance(alg);
    tmFact.init(truststore);//from www  .j  a v a  2  s  .  c o m

    sslContext.init(null, tmFact.getTrustManagers(), null);
}

From source file:com.iflytek.spider.protocol.httpclient.DummyX509TrustManager.java

/**
 * Constructor for DummyX509TrustManager.
 *//*from   w  ww.j a  v a2  s . c  om*/
public DummyX509TrustManager(KeyStore keystore) throws NoSuchAlgorithmException, KeyStoreException {
    super();
    String algo = TrustManagerFactory.getDefaultAlgorithm();
    TrustManagerFactory factory = TrustManagerFactory.getInstance(algo);
    factory.init(keystore);
    TrustManager[] trustmanagers = factory.getTrustManagers();
    if (trustmanagers.length == 0) {
        throw new NoSuchAlgorithmException(algo + " trust manager not supported");
    }
    this.standardTrustManager = (X509TrustManager) trustmanagers[0];
}