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:org.musicmount.io.server.dav.DAVResourceProvider.java

protected Sardine createSardine(final ServerFileSystem fileSystem) {
    /*//from  ww w . j  a  va2  s.c  om
     * extract user/password
     */
    String user = null;
    String password = null;
    if (fileSystem.getUserInfo() != null) {
        String[] userAndPassword = fileSystem.getUserInfo().split(":");
        user = userAndPassword[0];
        password = userAndPassword.length > 1 ? userAndPassword[1] : null;
    }

    /*
     * create customized sardine
     */
    return new SardineImpl(user, password, null) {
        @Override
        protected Registry<ConnectionSocketFactory> createDefaultSchemeRegistry() {
            ConnectionSocketFactory socketFactory;
            if ("https".equalsIgnoreCase(fileSystem.getScheme())) {
                socketFactory = createDefaultSecureSocketFactory();
            } else {
                socketFactory = createDefaultSocketFactory();
            }
            return RegistryBuilder.<ConnectionSocketFactory>create()
                    .register(fileSystem.getScheme(), socketFactory).build();
        }

        @Override
        protected ConnectionSocketFactory createDefaultSecureSocketFactory() {
            try { // trust anybody...
                SSLContext context = SSLContext.getInstance("TLS");
                X509TrustManager trustManager = new X509TrustManager() {
                    public void checkClientTrusted(X509Certificate[] xcs, String string)
                            throws CertificateException {
                    }

                    public void checkServerTrusted(X509Certificate[] xcs, String string)
                            throws CertificateException {
                    }

                    public X509Certificate[] getAcceptedIssuers() {
                        return new X509Certificate[0];
                    }
                };
                context.init(null, new TrustManager[] { trustManager }, null);
                return new SSLConnectionSocketFactory(context,
                        SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            } catch (NoSuchAlgorithmException | KeyManagementException e) {
                // should not happen...
            }
            return super.createDefaultSecureSocketFactory();
        }

        @Override
        protected <T> T execute(HttpRequestBase request, ResponseHandler<T> responseHandler)
                throws IOException {
            /*
             * Sardine re-executes a PUT request after a org.apache.http.NoHttpResponseException without resetting it...
             */
            if (request.isAborted()) {
                request.reset();
            }
            return super.execute(request, responseHandler);
        }

        @Override
        public ContentLengthInputStream get(String url, Map<String, String> headers) throws IOException {
            /*
             * abort rather than consume entity for better performance
             */
            final HttpGet get = new HttpGet(url);
            for (String header : headers.keySet()) {
                get.addHeader(header, headers.get(header));
            }
            // Must use #execute without handler, otherwise the entity is consumed already after the handler exits.
            final HttpResponse response = this.execute(get);
            VoidResponseHandler handler = new VoidResponseHandler();
            try {
                handler.handleResponse(response);
                // Will consume or abort the entity when the stream is closed.
                PositionInputStream positionInputStream = new PositionInputStream(
                        response.getEntity().getContent()) {
                    public void close() throws IOException {
                        if (getPosition() == response.getEntity().getContentLength()) {
                            EntityUtils.consume(response.getEntity());
                        } else { // partial read or unknown content length
                            get.abort();
                        }
                    }
                };
                return new ContentLengthInputStream(positionInputStream,
                        response.getEntity().getContentLength());
            } catch (IOException ex) {
                get.abort();
                throw ex;
            }
        }
    };
}

From source file:com.zacwolf.commons.crypto._CRYPTOfactory.java

public static KeyStore addSiteTrustChain(final String sitehostname, final int httpsport,
        final KeyStore keystore, final char[] passphrase) throws KeyStoreException, NoSuchAlgorithmException,
        CertificateException, IOException, KeyManagementException {
    final SSLContext context = SSLContext.getInstance("TLS");
    final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(keystore);//w  w  w.j  a va2s .c o  m
    final X509TrustManager dtm = (X509TrustManager) tmf.getTrustManagers()[0];
    final MyTrustManager tm = new MyTrustManager(dtm);
    context.init(null, new TrustManager[] { tm }, null);
    final SSLSocketFactory factory = context.getSocketFactory();
    final SSLSocket socket = (SSLSocket) factory.createSocket(sitehostname, httpsport);
    socket.setSoTimeout(10000);
    try {
        System.out.println("Starting SSL handshake...");
        socket.startHandshake();
        socket.close();
        System.out.println("Certificate for server " + sitehostname + " is already trusted");
    } catch (SSLException e) {
        final X509Certificate[] chain = tm.chain;
        if (chain == null) {
            System.err.println("Could not obtain server certificate chain");
            return keystore;
        }
        System.out.println("Server sent " + chain.length + " certificate(s):");
        for (int i = 0; i < chain.length; i++) {
            final X509Certificate cert = chain[i];
            MessageDigest.getInstance("SHA1").update(cert.getEncoded());
            MessageDigest.getInstance("MD5").update(cert.getEncoded());
            final String alias = sitehostname + "-" + (i + 1);
            keystore.setCertificateEntry(alias, cert);
            System.out.println("Added certificate to keystore using alias '" + alias + "'");
        }
    }
    return keystore;
}

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

public static HttpClient getHttpsClientWithProxy(byte[] sslCertificateBytes, String proxyAddress,
        int proxyPort) {
    DefaultHttpClient httpClient;//  w  ww . j  a v a2s.  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.sonatype.nexus.ssl.plugin.internal.TrustStoreImpl.java

@Override
public SSLContext getSSLContext() {
    SSLContext _sslcontext = this.sslcontext; // local variable allows concurrent removeTrustCertificate
    if (_sslcontext == null) {
        try {//  w w w . j a  va 2 s  . c o m
            _sslcontext = SSLContext.getInstance(SSLConnectionSocketFactory.TLS);
            _sslcontext.init(keyManagers, trustManagers, DEFAULT_RANDOM);
            this.sslcontext = _sslcontext;
        } catch (Exception e) {
            log.debug("Could not create SSL context", e);
            Throwables.throwIfUnchecked(e);
            throw new RuntimeException(e);
        }
    }
    return _sslcontext;
}

From source file:com.ibm.caas.CaaSResource.java

/**
 * Pass throughout CERTs [workaround]/*from   www .  ja v a 2  s  . co m*/
 */
public void relaxHostChecking() {

    // Override SSL Trust manager without certificate chains validation
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType) {
        }

    } };

    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

        // Hostname verification. 
        HostnameVerifier allHostsValid = new HostnameVerifier() {
            /**
             * Verify that the host name is an acceptable match with the server's authentication scheme.
             * @hostname - the host name
             * @session - SSLSession used on the connection to host
             * @return true if the host name is acceptable
             */
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };
        // Sets the default HostnameVerifier by all-trusting host verifier.
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (KeyManagementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:org.vsearchd.crawler.backend.BackendSessionHTTPS.java

private Scheme getHttpSslTheme(String url) throws Exception {
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, getTrustManager(), null);
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    SSLSocketFactory socketFactory = new SSLSocketFactory(sc, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    return new Scheme("https", Integer.valueOf(this.getBackendServer().getPort()), socketFactory);
}

From source file:com.microsoft.tfs.core.config.httpclient.internal.DefaultSSLProtocolSocketFactory.java

private SSLContext getSSLContext() throws NoSuchAlgorithmException {

    final String requestedProtocol = getRequestedProtocol();

    try {//ww  w .  j  a  va2  s. c  om
        return SSLContext.getInstance(requestedProtocol);
    } catch (final NoSuchAlgorithmException e) {
        log.error("Cannot create SSL context with the requested protocol " + requestedProtocol, e); //$NON-NLS-1$
        log.info("Using SSL context with the default protocol TLS"); //$NON-NLS-1$

        return SSLContext.getInstance("TLS"); //$NON-NLS-1$
    }
}

From source file:org.wso2.carbon.esb.rabbitmq.message.store.jira.ESBJAVA4569RabbiMQSSLStoreWithClientCertValidationTest.java

/**
 * Helper method to retrieve queue message from rabbitMQ
 *
 * @return result//w ww .j  ava2  s  .  c om
 * @throws Exception
 */
private static String consumeWithoutCertificate() throws Exception {
    String result = "";

    String basePath = TestConfigurationProvider.getResourceLocation()
            + "/artifacts/ESB/messageStore/rabbitMQ/SSL/";

    String truststoreLocation = basePath + "rabbitMQ/certs/client/rabbitstore";
    String keystoreLocation = basePath + "rabbitMQ/certs/client/keycert.p12";

    char[] keyPassphrase = "MySecretPassword".toCharArray();
    KeyStore ks = KeyStore.getInstance("PKCS12");
    ks.load(new FileInputStream(keystoreLocation), keyPassphrase);

    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(ks, keyPassphrase);

    char[] trustPassphrase = "rabbitstore".toCharArray();
    KeyStore tks = KeyStore.getInstance("JKS");
    tks.load(new FileInputStream(truststoreLocation), trustPassphrase);

    TrustManagerFactory tmf = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    tmf.init(tks);

    SSLContext c = SSLContext.getInstance("SSL");
    c.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    factory.setPort(5671);
    factory.useSslProtocol(c);

    Connection conn = factory.newConnection();
    Channel channel = conn.createChannel();

    GetResponse chResponse = channel.basicGet("WithClientCertQueue", true);
    if (chResponse != null) {
        byte[] body = chResponse.getBody();
        result = new String(body);
    }
    channel.close();
    conn.close();
    return result;
}

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./* w w  w  .  j a  v a2s  .c om*/
 *
 * @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);
    }
}