Example usage for javax.net.ssl SSLContext getInstance

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

Introduction

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

Prototype

public static SSLContext getInstance(String protocol) throws NoSuchAlgorithmException 

Source Link

Document

Returns a SSLContext object that implements the specified secure socket protocol.

Usage

From source file:com.lyndir.lhunath.opal.network.SSLFactory.java

private SSLFactory(final File keyStore, final String password) {

    try (InputStream keyStoreStream = new FileInputStream(keyStore)) {
        KeyStore store = KeyStore.getInstance("JKS");
        store.load(keyStoreStream, password.toCharArray());

        TrustManagerFactory tFactory = TrustManagerFactory.getInstance("SunX509");
        tFactory.init(store);//from   w  w  w.  ja  v  a 2s  .c  o  m

        context = SSLContext.getInstance("TLS");
        context.init(null, tFactory.getTrustManagers(), null);
    } catch (final KeyStoreException e) {
        throw new IllegalArgumentException(
                "Keystore type not supported or keystore could not be used to initialize trust.", e);
    } catch (final NoSuchAlgorithmException e) {
        throw new IllegalStateException("Key algorithm not supported.", e);
    } catch (final CertificateException e) {
        throw new IllegalArgumentException("Keystore could not be loaded.", e);
    } catch (final FileNotFoundException e) {
        throw new IllegalArgumentException("Keystore not found.", e);
    } catch (final IOException e) {
        throw new RuntimeException("Could not read the keys from the keystore.", e);
    } catch (final KeyManagementException e) {
        throw new RuntimeException("Could not use the keys for trust.", e);
    }
}

From source file:gobblin.security.ssl.SSLContextFactory.java

/**
 * Create a {@link SSLContext} instance/*  www .ja  v  a 2  s  . co  m*/
 *
 * @param keyStoreFile a p12 or jks file depending on key store type
 * @param keyStorePassword password to access the key store
 * @param keyStoreType type of key store
 * @param trustStoreFile a jks file
 * @param trustStorePassword password to access the trust store
 */
public static SSLContext createInstance(File keyStoreFile, String keyStorePassword, String keyStoreType,
        File trustStoreFile, String trustStorePassword) {
    if (!keyStoreType.equalsIgnoreCase(P12_STORE_TYPE_NAME)
            && !keyStoreType.equalsIgnoreCase(JKS_STORE_TYPE_NAME)) {
        throw new IllegalArgumentException("Unsupported keyStoreType: " + keyStoreType);
    }

    try {
        // Load KeyStore
        KeyStore keyStore = KeyStore.getInstance(keyStoreType);
        keyStore.load(toInputStream(keyStoreFile), keyStorePassword.toCharArray());

        // Load TrustStore
        KeyStore trustStore = KeyStore.getInstance(JKS_STORE_TYPE_NAME);
        trustStore.load(toInputStream(trustStoreFile), trustStorePassword.toCharArray());

        // Set KeyManger from keyStore
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(DEFAULT_ALGORITHM);
        kmf.init(keyStore, keyStorePassword.toCharArray());

        // Set TrustManager from trustStore
        TrustManagerFactory trustFact = TrustManagerFactory.getInstance(DEFAULT_ALGORITHM);
        trustFact.init(trustStore);

        // Set Context to TLS and initialize it
        SSLContext sslContext = SSLContext.getInstance(DEFAULT_PROTOCOL);
        sslContext.init(kmf.getKeyManagers(), trustFact.getTrustManagers(), null);

        return sslContext;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:bear.plugins.java.JenkinsCache.java

public static File download2(String jdkVersion, File jenkinsCache, File tempDestDir, String jenkinsUri,
        String user, String pass) {
    try {/*from w  w  w  . j ava  2  s  .co m*/
        Optional<JDKFile> optional = load(jenkinsCache, jenkinsUri, jdkVersion);

        if (!optional.isPresent()) {
            throw new RuntimeException("could not find: " + jdkVersion);
        }

        String uri = optional.get().filepath;

        //                agent.get()

        //                agent.get()

        SSLContext sslContext = SSLContext.getInstance("TLSv1");

        sslContext.init(null, new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                System.out.println("getAcceptedIssuers =============");
                return null;
            }

            public void checkClientTrusted(X509Certificate[] certs, String authType) {
                System.out.println("checkClientTrusted =============");
            }

            public void checkServerTrusted(X509Certificate[] certs, String authType) {
                System.out.println("checkServerTrusted =============");
            }
        } }, new SecureRandom());

        SSLSocketFactory sf = new SSLSocketFactory(sslContext);

        Scheme httpsScheme = new Scheme("https", 443, sf);
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(httpsScheme);

        DefaultHttpClient httpClient = new DefaultHttpClient(
                new PoolingClientConnectionManager(schemeRegistry));

        MechanizeAgent agent = new MechanizeAgent();
        Cookie cookie2 = agent.cookies().addNewCookie("gpw_e24", ".", "oracle.com");
        cookie2.getHttpCookie().setPath("/");
        cookie2.getHttpCookie().setSecure(false);

        CookieStore cookieStore = new BasicCookieStore();
        BasicClientCookie cookie = new BasicClientCookie("gpw_e24", ".");
        cookie.setDomain("oracle.com");
        cookie.setPath("/");
        cookie.setSecure(true);

        cookieStore.addCookie(cookie);

        httpClient.setCookieStore(cookieStore);

        HttpPost httppost = new HttpPost("https://login.oracle.com");

        httppost.setHeader("Authorization",
                "Basic " + new String(Base64.encodeBase64((user + ":" + pass).getBytes()), "UTF-8"));

        HttpResponse response = httpClient.execute(httppost);

        int code = response.getStatusLine().getStatusCode();

        if (code != 302) {
            System.out.println(IOUtils.toString(response.getEntity().getContent()));
            throw new RuntimeException("unable to auth: " + code);
        }

        //                EntityUtils.consumeQuietly(response.getEntity());

        httppost = new HttpPost(uri);

        response = httpClient.execute(httppost);

        code = response.getStatusLine().getStatusCode();

        if (code != 302) {
            System.out.println(IOUtils.toString(response.getEntity().getContent()));
            throw new RuntimeException("to download: " + uri);
        }

        File file = new File(tempDestDir, optional.get().name);
        HttpEntity entity = response.getEntity();

        final long length = entity.getContentLength();

        final CountingOutputStream os = new CountingOutputStream(new FileOutputStream(file));

        System.out.printf("Downloading %s to %s...%n", uri, file);

        Thread progressThread = new Thread(new Runnable() {
            double lastProgress;

            @Override
            public void run() {
                while (!Thread.currentThread().isInterrupted()) {
                    long copied = os.getCount();

                    double progress = copied * 100D / length;

                    if (progress != lastProgress) {
                        System.out.printf("\rProgress: %s%%", LangUtils.toConciseString(progress, 1));
                    }

                    lastProgress = progress;

                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        break;
                    }
                }
            }
        }, "progressThread");

        progressThread.start();

        ByteStreams.copy(entity.getContent(), os);

        progressThread.interrupt();

        System.out.println("Download complete.");

        return file;
    } catch (Exception e) {
        throw Exceptions.runtime(e);
    }
}

From source file:org.skfiy.typhon.rnsd.service.handler.AppleRechargingHandler.java

public AppleRechargingHandler() throws Exception {
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new java.security.SecureRandom());
    HC_BUILDER.setSslcontext(sc);//from  w ww .  j  av  a  2 s . c  o  m
}

From source file:com.daoke.mobileserver.test.TestHttps.java

public static String doPost(String url, String ctype, byte[] content, int connectTimeout, int readTimeout)
        throws Exception {
    HttpsURLConnection conn = null;
    OutputStream out = null;// w  w w .  ja va2s .c  o m
    String rsp = null;
    try {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
            SSLContext.setDefault(ctx);

            conn = getConnection(new URL(url), METHOD_POST, ctype);
            conn.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
            conn.setConnectTimeout(connectTimeout);
            conn.setReadTimeout(readTimeout);
        } catch (Exception e) {
            log.error("GET_CONNECTOIN_ERROR, URL = " + url, e);
            throw e;
        }
        try {
            out = conn.getOutputStream();
            out.write(content);
            rsp = getResponseAsString(conn);
        } catch (IOException e) {
            log.error("REQUEST_RESPONSE_ERROR, URL = " + url, e);
            throw e;
        }

    } finally {
        if (out != null) {
            out.close();
        }
        if (conn != null) {
            conn.disconnect();
        }
    }

    return rsp;
}

From source file:com.baasbox.android.HttpUrlConnectionClient.java

private static SSLSocketFactory createSocketFactory(Context context, int certStoreId, String certPassword) {
    TrustManagerFactory tmf;/*from w w  w  . j ava  2 s . c  o m*/
    InputStream in = null;
    try {
        in = context.getResources().openRawResource(certStoreId);
        KeyStore keyStore = KeyStore.getInstance("BKS");
        keyStore.load(in, certPassword.toCharArray());

        tmf = TrustManagerFactory.getInstance("X509");
        tmf.init(keyStore);

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

        return sslContext.getSocketFactory();
    } catch (Exception e) {
        throw new BaasRuntimeException(e);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                // swallow
            }
        }
    }
}

From source file:com.stratio.qa.utils.GosecSSOUtils.java

/**
 * This method provide dcos and sso token to be used to generate client cookie
 * @return cookieToken list of token generated
 * @throws Exception exception//  w  w w  . j a v a 2s  .  com
 */
public HashMap<String, String> ssoTokenGenerator() throws Exception {
    String protocol = "https://";
    HashMap<String, String> cookieToken = new HashMap<>();

    SSLContext sslContext = SSLContext.getInstance("SSL");
    // set up a TrustManager that trusts everything
    sslContext.init(null, ALL_TRUSTING_TRUST_MANAGER, new SecureRandom());
    HttpClientContext context = HttpClientContext.create();
    HttpGet httpGet = new HttpGet(protocol + ssoHost + "/login");
    HttpClient client = HttpClientBuilder.create().setSslcontext(sslContext)
            .setRedirectStrategy(new LaxRedirectStrategy())
            .setDefaultRequestConfig(RequestConfig.custom().setCircularRedirectsAllowed(true).build()).build();
    try {
        HttpResponse firstResponse = client.execute(httpGet, context);

        logger.debug(firstResponse.getStatusLine().toString());
        Document doc = Jsoup.parse(getStringFromIS(firstResponse.getEntity().getContent()));
        Elements code = doc.select("[name=lt]");
        String loginCode = code.attr("value");
        String executionCode = doc.select("[name=execution]").attr("value");
        for (Header oneHeader : firstResponse.getAllHeaders()) {
            logger.debug(oneHeader.getName() + ":" + oneHeader.getValue());
        }

        URI redirect = context.getRedirectLocations().get(context.getRedirectLocations().size() - 1);

        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("_eventId", "submit"));
        params.add(new BasicNameValuePair("submit", "LOGIN"));
        params.add(new BasicNameValuePair("username", userName));
        params.add(new BasicNameValuePair("password", passWord));
        params.add(new BasicNameValuePair("lt", loginCode));
        params.add(new BasicNameValuePair("execution", executionCode));
        HttpPost httpPost = new HttpPost(redirect);
        httpPost.setEntity(new UrlEncodedFormEntity(params));
        HttpResponse secondResponse = client.execute(httpPost, context);

        for (Header oneHeader : secondResponse.getAllHeaders()) {
            logger.debug(oneHeader.getName() + ":" + oneHeader.getValue());
        }

        HttpGet managementGet = new HttpGet(protocol + ssoHost + managementHost);
        client.execute(managementGet, context);

        for (Cookie oneCookie : context.getCookieStore().getCookies()) {
            logger.debug(oneCookie.getName() + ":" + oneCookie.getValue());
            cookieToken.put(oneCookie.getName(), oneCookie.getValue());
        }

    } catch (Exception e) {
        e.getStackTrace();
    }
    return cookieToken;
}

From source file:net.sf.jsignpdf.ssl.SSLInitializer.java

public static final void init() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException,
        CertificateException, IOException {
    if (Constants.RELAX_SSL_SECURITY) {
        LOGGER.debug("Relaxing SSL security.");

        //Details for the properties - http://docs.oracle.com/javase/7/docs/technotes/guides/security/jsse/JSSERefGuide.html
        //Workaround for http://sourceforge.net/tracker/?func=detail&atid=1037906&aid=3491269&group_id=216921
        System.setProperty("jsse.enableSNIExtension", "false");

        //just in case...
        System.setProperty("sun.security.ssl.allowUnsafeRenegotiation", "true");
        System.setProperty("sun.security.ssl.allowLegacyHelloMessages", "true");

        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }//from w w  w . j  a va 2s .  com
        });
    }

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

    HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
}

From source file:org.apache.servicemix.http.processors.CommonsHttpSSLSocketFactory.java

protected final void createUnmanagedFactory(SslParameters ssl) throws Exception {
    SSLContext context;/*ww  w .j a va2 s .c  om*/
    if (ssl.getProvider() == null) {
        context = SSLContext.getInstance(ssl.getProtocol());
    } else {
        context = SSLContext.getInstance(ssl.getProtocol(), ssl.getProvider());
    }
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(ssl.getKeyManagerFactoryAlgorithm());
    String keyStore = ssl.getKeyStore();
    if (keyStore == null) {
        keyStore = System.getProperty("javax.net.ssl.keyStore");
        if (keyStore == null) {
            throw new IllegalArgumentException(
                    "keyStore or system property javax.net.ssl.keyStore must be set");
        }
    }
    if (keyStore.startsWith("classpath:")) {
        try {
            String res = keyStore.substring(10);
            URL url = new ClassPathResource(res).getURL();
            keyStore = url.toString();
        } catch (IOException e) {
            throw new JBIException("Unable to find keyStore " + keyStore, e);
        }
    }
    String keyStorePassword = ssl.getKeyStorePassword();
    if (keyStorePassword == null) {
        keyStorePassword = System.getProperty("javax.net.ssl.keyStorePassword");
        if (keyStorePassword == null) {
            throw new IllegalArgumentException(
                    "keyStorePassword or system property javax.net.ssl.keyStorePassword must be set");
        }
    }
    String trustStore = ssl.getTrustStore();
    String trustStorePassword = null;
    if (trustStore == null) {
        trustStore = System.getProperty("javax.net.ssl.trustStore");
    }
    if (trustStore != null) {
        if (trustStore.startsWith("classpath:")) {
            try {
                String res = trustStore.substring(10);
                URL url = new ClassPathResource(res).getURL();
                trustStore = url.toString();
            } catch (IOException e) {
                throw new JBIException("Unable to find trustStore " + trustStore, e);
            }
        }
        trustStorePassword = ssl.getTrustStorePassword();
        if (trustStorePassword == null) {
            trustStorePassword = System.getProperty("javax.net.ssl.trustStorePassword");
            if (trustStorePassword == null) {
                throw new IllegalArgumentException(
                        "trustStorePassword or system property javax.net.ssl.trustStorePassword must be set");
            }
        }
    }
    KeyStore ks = KeyStore.getInstance(ssl.getKeyStoreType());
    ks.load(Resource.newResource(keyStore).getInputStream(), keyStorePassword.toCharArray());
    keyManagerFactory.init(ks,
            ssl.getKeyPassword() != null ? ssl.getKeyPassword().toCharArray() : keyStorePassword.toCharArray());
    if (trustStore != null) {
        KeyStore ts = KeyStore.getInstance(ssl.getTrustStoreType());
        ts.load(Resource.newResource(trustStore).getInputStream(), trustStorePassword.toCharArray());
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(ssl.getTrustManagerFactoryAlgorithm());
        trustManagerFactory.init(ts);
        context.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(),
                new java.security.SecureRandom());
    } else {
        context.init(keyManagerFactory.getKeyManagers(), null, new java.security.SecureRandom());
    }
    factory = context.getSocketFactory();
}

From source file:com.cloupia.feature.nimble.http.MySSLSocketFactory.java

public Socket createSocket(Socket socket, String host, int port, boolean flag)
        throws IOException, UnknownHostException {

    TrustManager[] trustAllCerts = getTrustManager();

    try {/*ww  w  . j  a v a 2  s .c  o m*/

        SSLContext sc = SSLContext.getInstance("SSL");

        sc.init(null, trustAllCerts, new java.security.SecureRandom());

        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

        SocketFactory socketFactory = HttpsURLConnection.getDefaultSSLSocketFactory();

        return socketFactory.createSocket(host, port);

    }

    catch (Exception ex) {

        throw new UnknownHostException("Problems to connect " + host + ex.toString());

    }

}