Example usage for javax.net.ssl HttpsURLConnection getDefaultSSLSocketFactory

List of usage examples for javax.net.ssl HttpsURLConnection getDefaultSSLSocketFactory

Introduction

In this page you can find the example usage for javax.net.ssl HttpsURLConnection getDefaultSSLSocketFactory.

Prototype

public static SSLSocketFactory getDefaultSSLSocketFactory() 

Source Link

Document

Gets the default static SSLSocketFactory that is inherited by new instances of this class.

Usage

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

@Override
public Socket createSocket(String host, int port, InetAddress localAddress, int localPort,
        HttpConnectionParams arg4) throws IOException, UnknownHostException, ConnectTimeoutException {
    TrustManager[] trustAllCerts = getTrustManager();

    try {/*from www . ja va 2s. 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());

    }

}

From source file:be.fedict.eid.idp.sp.protocol.openid.OpenIDSSLSocketFactory.java

/**
 * Install the OpenID SSL Socket Factory. Trusts the given server
 * certificate and all default trusted server certificates.
 * /*from w  ww .ja v a  2 s .com*/
 * @param serverCertificate
 *            SSL Certificate to trust
 * @throws NoSuchAlgorithmException
 *             could not get an SSLContext instance
 * @throws KeyManagementException
 *             failed to initialize the SSLContext
 * @throws KeyStoreException
 *             failed to intialize the {@link OpenIDTrustManager}
 */
public static void install(X509Certificate serverCertificate)
        throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
    SSLSocketFactory sslSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory();
    if (!(sslSocketFactory instanceof OpenIDSSLSocketFactory)) {
        LOG.debug("installing OpenID SSL Socket Factory...");
        OpenIDSSLSocketFactory openIDSSLSocketFactory = new OpenIDSSLSocketFactory(serverCertificate);
        HttpsURLConnection.setDefaultSSLSocketFactory(openIDSSLSocketFactory);
    } else {
        LOG.debug("OpenID SSL Socket Factory already installed.");
    }
}

From source file:com.example.mp_master.helper.UntrustedSSLSocketFactory.java

/**
 * Creates the default SSL socket factory.
 * This constructor is used exclusively to instantiate the factory for
 * {@link #getSocketFactory getSocketFactory}.
 * @throws NoSuchAlgorithmException //from w w w  .j a v a 2  s . c  o  m
 * @throws KeyManagementException 
 */
private UntrustedSSLSocketFactory() {
    super();
    this.nameResolver = null;
    TrustManager[] blindTrustMan = new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(X509Certificate[] c, String a) throws CertificateException {
        }

        public void checkServerTrusted(X509Certificate[] c, String a) throws CertificateException {
        }
    } };
    SSLContext sl = null;
    SSLSocketFactory sslf = null;
    try {
        sl = SSLContext.getInstance(TLS);
        sl.init(null, blindTrustMan, new java.security.SecureRandom());
        sslf = sl.getSocketFactory();
    } catch (Exception e) {
        e.printStackTrace();
        sslf = HttpsURLConnection.getDefaultSSLSocketFactory();
    }

    this.sslcontext = sl;
    this.socketfactory = sslf;

}

From source file:be.fedict.eid.idp.sp.protocol.openid.OpenIDSSLSocketFactory.java

/**
 * Installs the OpenID SSL Socket Factory. Trusts all server certificates.
 * For testing purposes only!//w w  w . j  a  v  a 2s. com
 * 
 * @throws NoSuchAlgorithmException
 *             could not get an SSLContext instance
 * @throws KeyManagementException
 *             failed to initialize the SSLContext
 */
public static void installAllTrusted() throws KeyManagementException, NoSuchAlgorithmException {
    SSLSocketFactory sslSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory();
    if (!(sslSocketFactory instanceof OpenIDSSLSocketFactory)) {
        LOG.debug("installing OpenID SSL Socket Factory...");
        OpenIDSSLSocketFactory openIDSSLSocketFactory = new OpenIDSSLSocketFactory();
        HttpsURLConnection.setDefaultSSLSocketFactory(openIDSSLSocketFactory);
        System.setProperty("java.protocol.handler.pkgs", "javax.net.ssl");
        HttpsURLConnection.setDefaultHostnameVerifier(
                org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    } else {
        LOG.debug("OpenID SSL Socket Factory already installed.");
    }
}

From source file:org.wso2.carbon.identity.relyingparty.saml.IssuerCertificateUtil.java

public static Certificate readCertFromUrl(String url) throws Exception {

    URL hostURL = null;//from   ww w.  j  a v  a 2  s . co  m
    String hostname = null;
    int port;
    SSLSocketFactory factory = null;
    SSLSocket socket = null;

    try {
        // Create the client socket
        hostURL = new URL(url);
        hostname = hostURL.getHost();

        // Check whether the url has a port stated explicitly. If its not present default to 443
        port = hostURL.getPort();
        if (port == -1) {
            port = 443;
        }
        factory = HttpsURLConnection.getDefaultSSLSocketFactory();
        socket = (SSLSocket) factory.createSocket(hostname, port);

        // Connect to the server
        socket.startHandshake();

        // Retrieve the server's certificate chain
        Certificate[] serverCerts = socket.getSession().getPeerCertificates();

        // The local certificate first followed by any certificate authorities.
        if (serverCerts != null && serverCerts.length > 0) {
            if (log.isDebugEnabled()) {
                log.debug("Return any associated certificates suceessfully" + url);
            }
            return serverCerts[0];
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Does not return any associated certificates" + url);
            }
            return null;
        }

    } finally {
        // Close the socket
        if (socket != null) {
            socket.close();
        }
    }
}

From source file:com.phonegap.FileTransfer.java

/**
 * This function will install a trust manager that will blindly trust all SSL 
 * certificates.  The reason this code is being added is to enable developers 
 * to do development using self signed SSL certificates on their web server.
 * /*from   ww  w . j a v a 2s  .com*/
 * The standard HttpsURLConnection class will throw an exception on self 
 * signed certificates if this code is not run.
 */
private void trustAllHosts() {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return new java.security.cert.X509Certificate[] {};
        }

        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }
    } };

    // Install the all-trusting trust manager
    try {
        // Backup the current SSL socket factory
        defaultSSLSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory();
        // Install our all trusting manager
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
        Log.e(LOG_TAG, e.getMessage(), e);
    }
}

From source file:com.gamesalutes.utils.EncryptUtils.java

/**
 * Returns <code>List</code> of strings in {@link #STRONG_CIPHER_SUITES} that
 * are supported by the default ssl socket factory.
 * /*from   w w  w. j a v a  2 s .c o m*/
 * @return <code>List</code> of supported strong cipher suites
 */
public static List<String> getSupportedStrongCipherSuites() {
    Set<String> suites = new HashSet<String>(
            Arrays.asList(HttpsURLConnection.getDefaultSSLSocketFactory().getSupportedCipherSuites()));
    List<String> enabledSuites = new ArrayList<String>();

    //get strong suites that are supported by the SSL factory
    for (String s : STRONG_CIPHER_SUITES) {
        if (suites.contains(s))
            enabledSuites.add(s);
    }
    return enabledSuites;
    //convert list into comma separated string for use in System.setProperty
}

From source file:com.mytwitter.Network.NetworkHelper.java

/**
 * Create a trust manager that does not validate SSL certificate chains.
 *//*from w  w  w .  j a v a  2 s. c o m*/
public void trustAllHosts() {

    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[] {};
        }

        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }
    } };

    // Install the all-trusting trust manager
    try {
        // Backup the current SSL socket factory
        defaultSSLSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory();
        // Install our all trusting manager
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.apache.flink.runtime.rest.RestServerEndpointITCase.java

@Before
public void setup() throws Exception {
    config.setString(WebOptions.UPLOAD_DIR, temporaryFolder.newFolder().getCanonicalPath());

    defaultSSLContext = SSLContext.getDefault();
    defaultSSLSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory();
    final SSLContext sslClientContext = SSLUtils.createRestClientSSLContext(config);
    if (sslClientContext != null) {
        SSLContext.setDefault(sslClientContext);
        HttpsURLConnection.setDefaultSSLSocketFactory(sslClientContext.getSocketFactory());
    }//from  w w w .  ja  v a 2s.co m

    RestServerEndpointConfiguration serverConfig = RestServerEndpointConfiguration.fromConfiguration(config);
    RestClientConfiguration clientConfig = RestClientConfiguration.fromConfiguration(config);

    final String restAddress = "http://localhost:1234";
    RestfulGateway mockRestfulGateway = mock(RestfulGateway.class);
    when(mockRestfulGateway.requestRestAddress(any(Time.class)))
            .thenReturn(CompletableFuture.completedFuture(restAddress));

    final GatewayRetriever<RestfulGateway> mockGatewayRetriever = () -> CompletableFuture
            .completedFuture(mockRestfulGateway);

    testHandler = new TestHandler(CompletableFuture.completedFuture(restAddress), mockGatewayRetriever,
            RpcUtils.INF_TIMEOUT);

    TestVersionHandler testVersionHandler = new TestVersionHandler(
            CompletableFuture.completedFuture(restAddress), mockGatewayRetriever, RpcUtils.INF_TIMEOUT);

    TestVersionSelectionHandler1 testVersionSelectionHandler1 = new TestVersionSelectionHandler1(
            CompletableFuture.completedFuture(restAddress), mockGatewayRetriever, RpcUtils.INF_TIMEOUT);

    TestVersionSelectionHandler2 testVersionSelectionHandler2 = new TestVersionSelectionHandler2(
            CompletableFuture.completedFuture(restAddress), mockGatewayRetriever, RpcUtils.INF_TIMEOUT);

    testUploadHandler = new TestUploadHandler(CompletableFuture.completedFuture(restAddress),
            mockGatewayRetriever, RpcUtils.INF_TIMEOUT);

    final StaticFileServerHandler<RestfulGateway> staticFileServerHandler = new StaticFileServerHandler<>(
            mockGatewayRetriever, CompletableFuture.completedFuture(restAddress), RpcUtils.INF_TIMEOUT,
            temporaryFolder.getRoot());

    final List<Tuple2<RestHandlerSpecification, ChannelInboundHandler>> handlers = Arrays.asList(
            Tuple2.of(new TestHeaders(), testHandler), Tuple2.of(TestUploadHeaders.INSTANCE, testUploadHandler),
            Tuple2.of(testVersionHandler.getMessageHeaders(), testVersionHandler),
            Tuple2.of(testVersionSelectionHandler1.getMessageHeaders(), testVersionSelectionHandler1),
            Tuple2.of(testVersionSelectionHandler2.getMessageHeaders(), testVersionSelectionHandler2),
            Tuple2.of(WebContentHandlerSpecification.getInstance(), staticFileServerHandler));

    serverEndpoint = new TestRestServerEndpoint(serverConfig, handlers);
    restClient = new TestRestClient(clientConfig);

    serverEndpoint.start();
    serverAddress = serverEndpoint.getServerAddress();
}

From source file:com.android.beyondemail.SSLSocketFactory.java

/**
 * Creates the default SSL socket factory.
 * This constructor is used exclusively to instantiate the factory for
 * {@link #getSocketFactory getSocketFactory}.
 *///from www .ja v  a 2  s.c o  m
private SSLSocketFactory() {
    super();
    sslcontext = null;
    socketfactory = HttpsURLConnection.getDefaultSSLSocketFactory();
    nameResolver = null;
}