Example usage for javax.net.ssl TrustManagerFactory init

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

Introduction

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

Prototype

public final void init(ManagerFactoryParameters spec) throws InvalidAlgorithmParameterException 

Source Link

Document

Initializes this factory with a source of provider-specific trust material.

Usage

From source file:org.wso2.extension.siddhi.store.mongodb.util.MongoTableUtils.java

private static SocketFactory extractSocketFactory(String trustStore, String trustStorePassword, String keyStore,
        String keyStorePassword) {
    TrustManager[] trustManagers;
    KeyManager[] keyManagers;//from  www  . j  ava 2  s.  co m

    try (InputStream trustStream = new FileInputStream(trustStore)) {
        char[] trustStorePass = trustStorePassword.toCharArray();
        KeyStore trustStoreJKS = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStoreJKS.load(trustStream, trustStorePass);
        TrustManagerFactory trustFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustFactory.init(trustStoreJKS);
        trustManagers = trustFactory.getTrustManagers();
    } catch (FileNotFoundException e) {
        throw new MongoTableException("Trust store file not found for secure connections to mongodb. "
                + "Trust Store file path : '" + trustStore + "'.", e);
    } catch (IOException e) {
        throw new MongoTableException(
                "I/O Exception in creating trust store for secure connections to mongodb. "
                        + "Trust Store file path : '" + trustStore + "'.",
                e);
    } catch (CertificateException e) {
        throw new MongoTableException("Certificates in the trust store could not be loaded for secure "
                + "connections to mongodb. Trust Store file path : '" + trustStore + "'.", e);
    } catch (NoSuchAlgorithmException e) {
        throw new MongoTableException("The algorithm used to check the integrity of the trust store cannot be "
                + "found. Trust Store file path : '" + trustStore + "'.", e);
    } catch (KeyStoreException e) {
        throw new MongoTableException("Exception in creating trust store, no Provider supports aKeyStoreSpi "
                + "implementation for the specified type. Trust Store file path : '" + trustStore + "'.", e);
    }

    try (InputStream keyStream = new FileInputStream(keyStore)) {
        char[] keyStorePass = keyStorePassword.toCharArray();
        KeyStore keyStoreJKS = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStoreJKS.load(keyStream, keyStorePass);
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStoreJKS, keyStorePass);
        keyManagers = keyManagerFactory.getKeyManagers();
    } catch (FileNotFoundException e) {
        throw new MongoTableException("Key store file not found for secure connections to mongodb. "
                + "Key Store file path : '" + keyStore + "'.", e);
    } catch (IOException e) {
        throw new MongoTableException(
                "I/O Exception in creating trust store for secure connections to mongodb. "
                        + "Key Store file path : '" + keyStore + "'.",
                e);
    } catch (CertificateException e) {
        throw new MongoTableException("Certificates in the trust store could not be loaded for secure "
                + "connections to mongodb. Key Store file path : '" + keyStore + "'.", e);
    } catch (NoSuchAlgorithmException e) {
        throw new MongoTableException("The algorithm used to check the integrity of the trust store cannot be "
                + "found. Key Store file path : '" + keyStore + "'.", e);
    } catch (KeyStoreException e) {
        throw new MongoTableException(
                "Exception in creating trust store, no Provider supports aKeyStoreSpi "
                        + "implementation for the specified type. Key Store file path : '" + keyStore + "'.",
                e);
    } catch (UnrecoverableKeyException e) {
        throw new MongoTableException(
                "Key in the keystore cannot be recovered. " + "Key Store file path : '" + keyStore + "'.", e);
    }

    try {
        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(keyManagers, trustManagers, null);
        SSLContext.setDefault(sslContext);
        return sslContext.getSocketFactory();
    } catch (KeyManagementException e) {
        throw new MongoTableException(
                "Error in validating the key in the key store/ trust store. " + "Trust Store file path : '"
                        + trustStore + "'. " + "Key Store file path : '" + keyStore + "'.",
                e);
    } catch (NoSuchAlgorithmException e) {
        throw new MongoTableException(
                " SSL Algorithm used to create SSL Socket Factory for mongodb connections " + "is not found.",
                e);
    }

}

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;/*from  www.j  av  a 2  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: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 ww. j ava2  s  .  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: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();//from  www. j  ava2s  .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 {// ww w  . j  a v a2 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: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);

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

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

/**
 * Constructor for DummyX509TrustManager.
 *///w ww . java2  s . co m
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];
}

From source file:com.cazoodle.crawl.DummyX509TrustManager.java

/**
 * Constructor for DummyX509TrustManager.
 */// w ww  .j  ava 2 s  . c  o m
public DummyX509TrustManager(KeyStore keystore) throws NoSuchAlgorithmException, KeyStoreException {
    super();
    TrustManagerFactory factory = TrustManagerFactory.getInstance("SunX509");
    factory.init(keystore);
    TrustManager[] trustmanagers = factory.getTrustManagers();
    if (trustmanagers.length == 0) {
        throw new NoSuchAlgorithmException("SunX509 trust manager not supported");
    }
    this.standardTrustManager = (X509TrustManager) trustmanagers[0];
}

From source file:com.silverpeas.util.security.SilverpeasX509TrustManager.java

public SilverpeasX509TrustManager(String trustStoreFile, char[] password) {
    InputStream fis = null;/*from  w  w  w  .  ja  v  a2s  . c  o m*/
    try {
        KeyStore trustore = KeyStore.getInstance(KeyStore.getDefaultType());
        fis = new FileInputStream(trustStoreFile);
        trustore.load(fis, password);
        TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
        tmf.init(trustore);
        TrustManager tms[] = tmf.getTrustManagers();
        for (TrustManager trustManager : tms) {
            if (trustManager instanceof X509TrustManager) {
                defaultTrustManager = (X509TrustManager) trustManager;
                return;
            }
        }
    } catch (IOException ioex) {
        logger.error("Couldn't load trustore " + trustStoreFile, ioex);
    } catch (GeneralSecurityException secEx) {
        logger.error("Couldn't create trustore " + trustStoreFile, secEx);
    } finally {
        IOUtils.closeQuietly(fis);
    }

}

From source file:org.wso2.msf4j.conf.SSLHandlerFactory.java

public SSLHandlerFactory(SSLConfig sslConfig) {
    String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm");
    if (algorithm == null) {
        algorithm = "SunX509";
    }/* w w  w .j av  a 2  s.c om*/
    try {
        KeyStore ks = getKeyStore(sslConfig.getKeyStore(), sslConfig.getKeyStorePassword());
        // Set up key manager factory to use our key store
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
        kmf.init(ks,
                sslConfig.getCertificatePassword() != null ? sslConfig.getCertificatePassword().toCharArray()
                        : sslConfig.getKeyStorePassword().toCharArray());
        KeyManager[] keyManagers = kmf.getKeyManagers();
        TrustManager[] trustManagers = null;
        if (sslConfig.getTrustKeyStore() != null) {
            this.needClientAuth = true;
            KeyStore tks = getKeyStore(sslConfig.getTrustKeyStore(), sslConfig.getTrustKeyStorePassword());
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm);
            tmf.init(tks);
            trustManagers = tmf.getTrustManagers();
        }
        serverContext = SSLContext.getInstance(protocol);
        serverContext.init(keyManagers, trustManagers, null);
    } catch (UnrecoverableKeyException | KeyManagementException | NoSuchAlgorithmException | KeyStoreException
            | IOException e) {
        throw new IllegalArgumentException("Failed to initialize the server-side SSLContext", e);
    }
}