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:Main.java

public static void main(String[] argv) throws Exception {
    int port = 443;
    String hostname = "hostname";
    SSLSocketFactory factory = HttpsURLConnection.getDefaultSSLSocketFactory();
    SSLSocket socket = (SSLSocket) factory.createSocket(hostname, port);

    socket.startHandshake();/*w w  w. j  av  a  2 s  .co  m*/

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

    socket.close();
}

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    SSLSocketFactory factory = HttpsURLConnection.getDefaultSSLSocketFactory();
    SSLSocket socket = (SSLSocket) factory.createSocket("127.0.0.1", 9999);
    socket.startHandshake();//from w ww .ja  v a2 s .c  om
    SSLSession session = socket.getSession();
    java.security.cert.Certificate[] servercerts = session.getPeerCertificates();

    List mylist = new ArrayList();
    for (int i = 0; i < servercerts.length; i++) {
        mylist.add(servercerts[i]);
    }

    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    CertPath cp = cf.generateCertPath(mylist);

    FileOutputStream f = new FileOutputStream("CertPath.dat");
    ObjectOutputStream b = new ObjectOutputStream(f);
    b.writeObject(cp);

}

From source file:test.integ.be.fedict.trust.util.SSLTrustManager.java

public static synchronized void initialize() {

    LOG.debug("initialize");
    if (null == socketFactory) {

        initSocketFactory();/*from   w  w  w.  j  a va2  s  .c  o m*/
        HttpsURLConnection.setDefaultSSLSocketFactory(socketFactory);
    } else {
        if (false == socketFactory.equals(HttpsURLConnection.getDefaultSSLSocketFactory()))
            throw new RuntimeException("wrong SSL socket factory installed");
    }
}

From source file:com.bytelightning.opensource.pokerface.HelloWorldScriptTest.java

@BeforeClass
public static void setUpBeforeClass() throws Exception {
    PrevSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory();
    PrevHostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier();

    proxy = new PokerFace();
    XMLConfiguration conf = new XMLConfiguration();
    conf.load(ProxySpecificTest.class.getResource("/HelloWorldTestConfig.xml"));
    proxy.config(conf);/*ww  w.  ja v a2s.  co  m*/
    boolean started = proxy.start();
    Assert.assertTrue("Successful proxy start", started);

    SSLContext sc = SSLContext.getInstance("TLS");
    TrustManager[] trustAllCertificates = { new X509TrustAllManager() };
    sc.init(null, trustAllCertificates, new SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true; // Just allow them all.
        }
    });

}

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

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

    TrustManager[] trustAllCerts = getTrustManager();

    try {//from   w w  w . j  av  a2 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());

    }

}

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 {/*w ww  .  j a  v  a  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:org.ops4j.pax.url.mvn.internal.HttpClients.java

private static PoolingHttpClientConnectionManager createConnManager(PropertyResolver resolver, String pid) {
    boolean SSL_INSECURE = getBoolean(resolver, "maven.wagon.http.ssl.insecure",
            !getBoolean(resolver, pid + "certificateCheck", false));
    boolean IGNORE_SSL_VALIDITY_DATES = getBoolean(resolver, "maven.wagon.http.ssl.ignore.validity.dates",
            false);//from   www  . j av a  2  s  .  c om
    boolean SSL_ALLOW_ALL = getBoolean(resolver, "maven.wagon.http.ssl.allowall",
            !getBoolean(resolver, pid + "certificateCheck", false));
    boolean PERSISTENT_POOL = getBoolean(resolver, "maven.wagon.http.pool", true);
    int MAX_CONN_PER_ROUTE = getInteger(resolver, "maven.wagon.httpconnectionManager.maxPerRoute", 20);
    int MAX_CONN_TOTAL = getInteger(resolver, "maven.wagon.httpconnectionManager.maxTotal", 40);

    String sslProtocolsStr = getProperty(resolver, "https.protocols", null);
    String cipherSuitesStr = getProperty(resolver, "https.cipherSuites", null);
    String[] sslProtocols = sslProtocolsStr != null ? sslProtocolsStr.split(" *, *") : null;
    String[] cipherSuites = cipherSuitesStr != null ? cipherSuitesStr.split(" *, *") : null;

    SSLConnectionSocketFactory sslConnectionSocketFactory;
    if (SSL_INSECURE) {
        try {
            SSLContext sslContext = new SSLContextBuilder().useSSL()
                    .loadTrustMaterial(null, new RelaxedTrustStrategy(IGNORE_SSL_VALIDITY_DATES)).build();
            sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, sslProtocols, cipherSuites,
                    SSL_ALLOW_ALL ? SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER
                            : SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        } catch (Exception ex) {
            throw new SSLInitializationException(ex.getMessage(), ex);
        }
    } else {
        sslConnectionSocketFactory = new SSLConnectionSocketFactory(
                HttpsURLConnection.getDefaultSSLSocketFactory(), sslProtocols, cipherSuites,
                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    }

    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.INSTANCE)
            .register("https", sslConnectionSocketFactory).build();

    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(registry);
    if (PERSISTENT_POOL) {
        connManager.setDefaultMaxPerRoute(MAX_CONN_PER_ROUTE);
        connManager.setMaxTotal(MAX_CONN_TOTAL);
    } else {
        connManager.setMaxTotal(1);
    }

    boolean soKeepAlive = getBoolean(resolver, pid + ServiceConstants.PROPERTY_SOCKET_SO_KEEPALIVE, false);
    int soLinger = getInteger(resolver, pid + ServiceConstants.PROPERTY_SOCKET_SO_LINGER, -1);
    boolean soReuseAddress = getBoolean(resolver, pid + ServiceConstants.PROPERTY_SOCKET_SO_REUSEADDRESS,
            false);
    boolean soTcpNoDelay = getBoolean(resolver, pid + ServiceConstants.PROPERTY_SOCKET_TCP_NODELAY, true);
    //        int soTimeout = getInteger( resolver, pid + ServiceConstants.PROPERTY_SOCKET_SO_TIMEOUT, 0 );
    SocketConfig socketConfig = SocketConfig.custom().setSoKeepAlive(soKeepAlive) // default false
            .setSoLinger(soLinger) // default -1
            .setSoReuseAddress(soReuseAddress) // default false
            .setTcpNoDelay(soTcpNoDelay) // default true
            .setSoTimeout(0) // default 0, but set in org.apache.http.impl.conn.CPoolProxy.setSocketTimeout()
            // this value is not used
            .build();
    connManager.setDefaultSocketConfig(socketConfig);

    int bufferSize = getInteger(resolver, pid + ServiceConstants.PROPERTY_CONNECTION_BUFFER_SIZE, 8192);
    ConnectionConfig connectionConfig = ConnectionConfig.custom().setBufferSize(bufferSize) // default 8192
            .setFragmentSizeHint(bufferSize) // default 'buffer size'
            .build();
    connManager.setDefaultConnectionConfig(connectionConfig);

    return connManager;
}

From source file:org.qi4j.library.http.AbstractSecureJettyTest.java

@BeforeClass
public static void beforeSecureClass() throws IOException, GeneralSecurityException {
    defaultHostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier();
    defaultSSLSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory();
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {

        public boolean verify(String string, SSLSession ssls) {
            return true;
        }/* w  ww . j av a  2 s .  c o  m*/

    });
    KeyStore truststore = KeyStore.getInstance("JCEKS");
    truststore.load(new FileInputStream(TRUSTSTORE_FILE), KS_PASSWORD.toCharArray());
    SSLContext sslCtx = SSLContext.getInstance("TLS");
    TrustManagerFactory caTrustManagerFactory = TrustManagerFactory.getInstance(getX509Algorithm());
    caTrustManagerFactory.init(truststore);
    sslCtx.init(null, caTrustManagerFactory.getTrustManagers(), null);
    HttpsURLConnection.setDefaultSSLSocketFactory(sslCtx.getSocketFactory());
}

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

public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort)
        throws IOException, UnknownHostException {

    TrustManager[] trustAllCerts = getTrustManager();

    try {//from ww  w.j  av a2  s .  c  om

        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, clientHost, clientPort);

    }

    catch (Exception ex) {

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

    }

}

From source file:test.integ.be.fedict.trust.XKMSTrustTest.java

@Test
public void testValidateUnilateralTLSTrust() throws Exception {
    LOG.debug("validate using unilateral TLS Trust.");

    // Retrieve server public key
    SSLTrustManager.initialize();//w  ww .  ja v a  2  s.  c  o m
    SSLSocketFactory factory = HttpsURLConnection.getDefaultSSLSocketFactory();
    SSLSocket socket = (SSLSocket) factory.createSocket(TestUtils.XKMS_WS_HOST, port);
    socket.startHandshake();
    Certificate[] serverCerts = socket.getSession().getPeerCertificates();
    PublicKey publicKey = serverCerts[0].getPublicKey();
    LOG.debug("server public key: " + publicKey);
    socket.close();

    /*
     * Override default verification that CN of server SSL certificate has
     * to be equal to the hostname.
     */
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return hostname.equals(TestUtils.XKMS_WS_HOST);
        }
    });

    // setup
    List<X509Certificate> signCertificateChain = TestUtils.getSignCertificateChain();
    XKMS2Client client = new XKMS2Client(
            "https://" + TestUtils.XKMS_WS_HOST + ":" + port + TestUtils.XKMS_WS_CONTEXT_PATH);
    client.setServicePublicKey(publicKey);

    /*
     * Operate: validate non repudiation
     */
    client.validate(TrustServiceDomains.BELGIAN_EID_NON_REPUDIATION_TRUST_DOMAIN, signCertificateChain);
}