Example usage for javax.net.ssl TrustManagerFactory getInstance

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

Introduction

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

Prototype

public static final TrustManagerFactory getInstance(String algorithm) throws NoSuchAlgorithmException 

Source Link

Document

Returns a TrustManagerFactory object that acts as a factory for trust managers.

Usage

From source file:software.betamax.util.DynamicSelfSignedSslEngineSource.java

private void initializeSSLContext() {
    String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm");
    if (algorithm == null) {
        algorithm = "SunX509";
    }/*ww w.j  a  v a  2  s . c  o m*/

    try {
        final KeyStore ks = KeyStore.getInstance("JKS");
        // ks.load(new FileInputStream("keystore.jks"),
        // "changeit".toCharArray());
        ks.load(new FileInputStream(keyStoreFile), PASSWORD.toCharArray());

        // Set up key manager factory to use our key store
        final KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
        kmf.init(ks, PASSWORD.toCharArray());

        // Set up a trust manager factory to use our key store
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm);
        tmf.init(ks);

        TrustManager[] trustManagers = new TrustManager[] { new X509TrustManager() {
            // TrustManager that trusts all servers
            @Override
            public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        } };

        KeyManager[] keyManagers = kmf.getKeyManagers();

        // Initialize the SSLContext to work with our key managers.
        sslContext = SSLContext.getInstance(PROTOCOL);
        sslContext.init(keyManagers, trustManagers, null);
    } catch (final Exception e) {
        throw new Error("Failed to initialize the server-side SSLContext", e);
    }
}

From source file:org.wso2.carbon.apimgt.integration.client.util.Utils.java

private static SSLSocketFactory initSSLConnection(KeyStore keyStore, String keyStorePassword,
        KeyStore trustStore)//from   w ww . j av  a 2s.  c  om
        throws NoSuchAlgorithmException, UnrecoverableKeyException, KeyStoreException, KeyManagementException {
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KEY_MANAGER_TYPE);
    keyManagerFactory.init(keyStore, keyStorePassword.toCharArray());
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TRUST_MANAGER_TYPE);
    trustManagerFactory.init(trustStore);

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

From source file:org.globus.gsi.jsse.SSLConfigurator.java

private void configureContext() throws GlobusSSLConfigurationException {

    ManagerFactoryParameters parameters = getCertPathParameters();
    TrustManager[] trustManagers;
    try {/*from  w  w w.  jav a2 s  . co  m*/
        TrustManagerFactory fact = TrustManagerFactory.getInstance("GSI");
        fact.init(parameters);
        trustManagers = fact.getTrustManagers();
    } catch (NoSuchAlgorithmException e1) {
        throw new GlobusSSLConfigurationException(e1);
    } catch (InvalidAlgorithmParameterException e) {
        throw new GlobusSSLConfigurationException(e);
    }

    KeyManager[] keyManagers = loadKeyManagers();

    SecureRandom secureRandom = loadSecureRandom();

    sslContext = loadSSLContext();

    try {
        sslContext.init(keyManagers, trustManagers, secureRandom);
    } catch (KeyManagementException e) {
        throw new GlobusSSLConfigurationException(e);
    }

}

From source file:br.com.ararati.operacoes.SocketFactory.java

public TrustManager[] createTrustManagers()
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
    KeyStore trustStore = KeyStore.getInstance("JKS");

    trustStore.load(new FileInputStream(fileCacerts), "changeit".toCharArray());
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(trustStore);
    return trustManagerFactory.getTrustManagers();
}

From source file:org.gw2InfoViewer.factories.HttpsConnectionFactory.java

public static HttpClient getHttpsClientWithProxy(byte[] sslCertificateBytes, String proxyAddress,
        int proxyPort) {
    DefaultHttpClient httpClient;//  w  w  w.j a v  a 2 s.c o m
    Certificate[] sslCertificate;
    HttpHost proxy;

    httpClient = new DefaultHttpClient();
    try {
        sslCertificate = convertByteArrayToCertificate(sslCertificateBytes);

        TrustManagerFactory tf = TrustManagerFactory.getInstance("X509");
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(null);
        for (int i = 0; i < sslCertificate.length; i++) {
            ks.setCertificateEntry("StartCom" + i, sslCertificate[i]);
        }

        tf.init(ks);
        TrustManager[] tm = tf.getTrustManagers();

        SSLContext sslCon = SSLContext.getInstance("SSL");
        sslCon.init(null, tm, new SecureRandom());
        SSLSocketFactory socketFactory = new SSLSocketFactory(ks);
        Scheme sch = new Scheme("https", 443, socketFactory);

        proxy = new HttpHost(proxyAddress, proxyPort, "https");
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

        httpClient.getConnectionManager().getSchemeRegistry().register(sch);
    } catch (CertificateException | NoSuchAlgorithmException | KeyStoreException | IOException
            | KeyManagementException | UnrecoverableKeyException ex) {
        Logger.getLogger(HttpsConnectionFactory.class.getName()).log(Level.SEVERE, null, ex);
    }

    return httpClient;
}

From source file:com.bt.pi.api.http.SimpleHttpsServerFactoryBean.java

protected HttpServer getInitializedServer(InetSocketAddress address) throws IOException {
    HttpsServer server = HttpsServer.create(address, getBacklog());
    try {/*from   w  w w. j  a va  2  s.c  om*/
        SSLContext sslContext = SSLContext.getInstance(sslContextProtocol);

        KeyStore ks = KeyStore.getInstance(keyStoreType);
        InputStream is = keyStoreLocation.getInputStream();
        try {
            ks.load(is, password);
        } catch (EOFException e) {
            LOG.warn(String.format(
                    "Unable to load certificate store %s. This may be possible because https isn't enabled with a valid certificate",
                    keyStoreLocation));
            return null;
        }

        KeyManagerFactory kmf = KeyManagerFactory.getInstance(keyManagerAlgorithm);
        kmf.init(ks, password);

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(trustManagerAlgorithm);
        tmf.init(ks);

        sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

        final SSLEngine m_engine = sslContext.createSSLEngine();

        server.setHttpsConfigurator(new HttpsConfigurator(sslContext) {
            public void configure(HttpsParameters params) {
                params.setSSLParameters(getSSLContext().getDefaultSSLParameters());
                params.setNeedClientAuth(false);
                params.setWantClientAuth(false);
                params.setCipherSuites(m_engine.getEnabledCipherSuites());
                params.setProtocols(m_engine.getEnabledProtocols());
            }
        });
    } catch (Throwable e) {
        throw new IOException("initializing HttpsServer failed due to exception", e);
    }
    return server;
}

From source file:com.github.mrstampy.gameboot.otp.OtpTestConfiguration.java

private SSLContext createContext(KeyStore keystore, KeyManagerFactory kmf) throws Exception {
    TrustManagerFactory trustFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustFactory.init(keystore);//from  w  ww . ja v  a  2s  .  c  o m

    SSLContext sslContext = SSLContext.getInstance(PROTOCOL);
    sslContext.init(kmf == null ? null : kmf.getKeyManagers(), trustFactory.getTrustManagers(), null);

    return sslContext;
}

From source file:org.thingsboard.rule.engine.mqtt.credentials.CertPemClientCredentials.java

private TrustManagerFactory createAndInitTrustManagerFactory() throws Exception {
    X509Certificate caCertHolder;
    caCertHolder = readCertFile(caCert);

    KeyStore caKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    caKeyStore.load(null, null);// w  w w  .  ja va 2 s  .co m
    caKeyStore.setCertificateEntry("caCert-cert", caCertHolder);

    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(caKeyStore);
    return trustManagerFactory;
}

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.//ww  w.  j  a  va 2 s .co 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.wso2.carbon.identity.application.authentication.endpoint.util.TenantMgtAdminServiceClient.java

/**
 * Create basic SSL connection factory/*from w ww .j  a v a  2s  . c  o m*/
 *
 * @throws AuthenticationException
 */
public static void initMutualSSLConnection(boolean hostNameVerificationEnabled) throws AuthenticationException {

    try {
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(keyManagerType);
        keyManagerFactory.init(keyStore, keyStorePassword);
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(trustManagerType);
        trustManagerFactory.init(trustStore);

        // Create and initialize SSLContext for HTTPS communication
        SSLContext sslContext = SSLContext.getInstance(protocol);

        if (hostNameVerificationEnabled) {
            sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
            sslSocketFactory = sslContext.getSocketFactory();

            if (log.isDebugEnabled()) {
                log.debug("Mutual SSL Client initialized with Hostname Verification enabled");
            }
        } else {
            // All the code below is to overcome host name verification failure we get in certificate
            // validation due to self signed certificate.

            // Create empty HostnameVerifier
            HostnameVerifier hv = new HostnameVerifier() {
                @Override
                public boolean verify(String urlHostName, SSLSession session) {
                    return true;
                }
            };

            // Create a trust manager that does not validate certificate chains
            TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
                @Override
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return new java.security.cert.X509Certificate[0];
                }

                @Override
                public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
                    /*
                         skipped implementation
                    */
                }

                @Override
                public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
                    /*
                         skipped implementation
                     */
                }
            } };

            sslContext.init(keyManagerFactory.getKeyManagers(), trustAllCerts,
                    new java.security.SecureRandom());

            if (log.isDebugEnabled()) {
                log.debug("SSL Context is initialized with trust manager for excluding certificate validation");
            }
            SSLContext.setDefault(sslContext);
            sslSocketFactory = sslContext.getSocketFactory();
            HttpsURLConnection.setDefaultHostnameVerifier(hv);

            if (log.isDebugEnabled()) {
                log.debug("Mutual SSL Client initialized with Hostname Verification disabled");
            }
        }
    } catch (UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException
            | KeyManagementException e) {
        throw new AuthenticationException("Error while trying to load Trust Store.", e);
    }
}