Example usage for javax.net.ssl SSLContext getSocketFactory

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

Introduction

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

Prototype

public final SSLSocketFactory getSocketFactory() 

Source Link

Document

Returns a SocketFactory object for this context.

Usage

From source file:davmail.util.ClientCertificateTest.java

public void testClientSocket() throws NoSuchAlgorithmException, KeyStoreException, IOException,
        CertificateException, KeyManagementException, UnrecoverableKeyException {

    //System.setProperty("javax.net.ssl.trustStoreProvider", "SunMSCAPI");
    //System.setProperty("javax.net.ssl.trustStoreType", "Windows-ROOT");
    System.setProperty("javax.net.ssl.trustStore", "cacerts");
    System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
    System.setProperty("javax.net.ssl.trustStoreType", "JKS");

    String algorithm = KeyManagerFactory.getDefaultAlgorithm();
    if ("SunX509".equals(algorithm)) {
        algorithm = "NewSunX509";
    } else if ("IbmX509".equals(algorithm)) {
        algorithm = "NewIbmX509";
    }//  www  .j  a v  a  2s  .  c om

    Provider sunMSCAPI = new sun.security.mscapi.SunMSCAPI();
    //Security.insertProviderAt(sunMSCAPI, 1);
    KeyStore keyStore = KeyStore.getInstance("Windows-MY", sunMSCAPI);
    keyStore.load(null, null);

    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(algorithm);
    keyManagerFactory.init(keyStore, null);

    // Get a list of key managers
    KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();

    // Walk through the key managers and replace all X509 Key Managers with
    // a specialized wrapped DavMail X509 Key Manager
    for (int i = 0; i < keyManagers.length; i++) {
        KeyManager keyManager = keyManagers[i];
        if (keyManager instanceof X509KeyManager) {
            keyManagers[i] = new DavMailX509KeyManager((X509KeyManager) keyManager);
        }
    }

    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(keyManagers, null, null);
    SSLSocketFactory sockFactory = sslContext.getSocketFactory();
    SSLSocket sslSock = (SSLSocket) sockFactory.createSocket("localhost", 443);
    sslSock.startHandshake();

}

From source file:edu.mayo.xsltserver.controller.XsltServerController.java

public XsltServerController() {
    super();/*  www. j av  a  2s .c  o  m*/
    try {
        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, TRUST_ALL_CERTS, new java.security.SecureRandom());
        // Create an ssl socket factory with our all-trusting manager
        this.sslSocketFactory = sslContext.getSocketFactory();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:io.github.retz.web.Client.java

protected Client(URI uri, Authenticator authenticator, boolean checkCert) {
    this.uri = Objects.requireNonNull(uri);
    this.authenticator = Objects.requireNonNull(authenticator);
    this.checkCert = checkCert;
    if (uri.getScheme().equals("https") && !checkCert) {
        LOG.warn(/*  w  w w  .  j  a  v  a 2  s . c  o m*/
                "DANGER ZONE: TLS certificate check is disabled. Set 'retz.tls.insecure = false' at config file to supress this message.");
        try {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, new TrustManager[] { new WrongTrustManager() }, new java.security.SecureRandom());
            socketFactory = sc.getSocketFactory();
            hostnameVerifier = new NoOpHostnameVerifier();
        } catch (NoSuchAlgorithmException e) {
            throw new AssertionError(e.toString());
        } catch (KeyManagementException e) {
            throw new AssertionError(e.toString());
        }
    } else {
        socketFactory = null;
        hostnameVerifier = null;
    }
    this.retz = Retz.connect(uri, authenticator, socketFactory, hostnameVerifier);
    System.setProperty("http.agent", Client.VERSION_STRING);
}

From source file:org.thoughtcrime.ssl.pinning.PinningSSLSocketFactory.java

/**
 * Constructs a PinningSSLSocketFactory with a set of valid pins.
 *
 * @param pins An array of encoded pins to match a seen certificate
 *             chain against. A pin is a hex-encoded hash of a X.509 certificate's
 *             SubjectPublicKeyInfo. A pin can be generated using the provided pin.py
 *             script: python ./tools/pin.py certificate_file.pem
 *
 * @param enforceUntilTimestampMillis A timestamp (in milliseconds) when pins will stop being
 *                                    enforced.  Normal non-pinned certificate validation
 *                                    will continue.  Set this to some period after your build
 *                                    date, or to 0 to enforce pins forever.
 *///w  w  w. ja v a2  s .co  m

public PinningSSLSocketFactory(Context context, String[] pins, long enforceUntilTimestampMillis)
        throws UnrecoverableKeyException, KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
    super(null);

    final SystemKeyStore keyStore = SystemKeyStore.getInstance(context);
    final SSLContext pinningSslContext = SSLContext.getInstance(TLS);
    final TrustManager[] pinningTrustManagers = initializePinningTrustManagers(keyStore, pins,
            enforceUntilTimestampMillis);

    pinningSslContext.init(null, pinningTrustManagers, null);
    this.pinningSocketFactory = pinningSslContext.getSocketFactory();
}

From source file:net.Downloader.java

public void run() {
    OutputStream os = null;//from   w  w  w.jav a 2s .co m
    InputStream is = null;

    ProgressListener progressListener = new ProgressListener();
    try {
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[] { new SSLManager() };

        // Install the all-trusting trust manager
        final SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

        // Create all-trusting host name verifier
        HostnameVerifier allHostsValid = new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };

        // Install the all-trusting host verifier
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

        os = new FileOutputStream(fl);
        is = conn.getInputStream();

        CountingStream dcount = new CountingStream(os);
        dcount.setListener(progressListener);

        status = "Downloading";
        // begin transfer by writing to dcount, not os.
        IOUtils.copy(is, dcount);

    } catch (UnknownHostException u) {
        System.err.println("Uknown Host2");
        u.printStackTrace();
    } catch (Exception e) {
        System.out.println(e);
    } finally {
        try {
            status = "Finished";
            if (os != null) {
                os.close();
            }
            if (is != null) {
                is.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

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

/**
 * Create a new SSL socket factory that is tolerant of self-signed
 * certificates.//from  ww w.  ja v  a2s  . c  o m
 *
 * @throws IOException
 * @throws CertificateException
 */
private SSLSocketFactory getStandardSocketFactory(final HttpConnectionParams params)
        throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, CertificateException,
        IOException {

    synchronized (lock) {
        if (standardSocketFactory == null) {
            final SSLContext context = getSSLContext();

            /* Use the default x509 trust manager. */
            context.init(null, new TrustManager[] { new DefaultX509TrustManager(null) }, null);

            standardSocketFactory = context.getSocketFactory();
        }

        return standardSocketFactory;
    }
}

From source file:ee.ria.xroad.proxy.clientproxy.FastestConnectionSelectingSSLSocketFactory.java

FastestConnectionSelectingSSLSocketFactory(SSLContext sslContext, String[] supportedCipherSuites) {
    super(sslContext, null, supportedCipherSuites, null);
    this.sslContext = sslContext;
    this.socketfactory = sslContext.getSocketFactory();
}

From source file:org.fineract.module.stellar.fineractadapter.RestAdapterProvider.java

OkHttpClient createClient() {

    final OkHttpClient client = new OkHttpClient();

    final TrustManager[] certs = new TrustManager[] { new X509TrustManager() {

        @Override/*from   w  ww  . j a va 2  s .  c o  m*/
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

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

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

    SSLContext ctx = null;
    try {
        ctx = SSLContext.getInstance("TLS");
        ctx.init(null, certs, new SecureRandom());
    } catch (final java.security.GeneralSecurityException ignored) {
    }

    try {
        client.setHostnameVerifier((hostname, session) -> true);
        if (ctx != null) {
            client.setSslSocketFactory(ctx.getSocketFactory());
        }
    } catch (final Exception ignored) {
    }

    return client;
}

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

/**
 * Create a new SSL socket factory that is tolerant of self-signed
 * certificates.//from ww  w  .j a v  a  2s.  co m
 *
 * @throws NoSuchAlgorithmException
 * @throws KeyStoreException
 * @throws KeyManagementException
 */
private SSLSocketFactory getSelfSignedSocketFactory(final HttpConnectionParams params)
        throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException {
    synchronized (lock) {
        if (selfSignedSocketFactory == null) {
            final SSLContext context = getSSLContext();

            /* Use the self-signed x509 trust manager. */
            context.init(null, new TrustManager[] { new SelfSignedX509TrustManager(null) }, null);

            selfSignedSocketFactory = context.getSocketFactory();
        }

        return selfSignedSocketFactory;
    }
}

From source file:org.apache.hadoop.net.HopsSSLSocketFactory.java

public Socket createSocket() throws IOException, UnknownHostException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Creating SSL client socket");
    }//from   w  w  w  . j  a v  a2s .  com
    if (conf.getBoolean(FORCE_CONFIGURE, false)) {
        setConf(conf);
    }
    SSLContext sslCtx = initializeSSLContext();
    SSLSocketFactory socketFactory = sslCtx.getSocketFactory();
    return socketFactory.createSocket();
}