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:it.zero11.acme.Acme.java

private static SSLContext getTrustAllCertificateSSLContext()
        throws NoSuchAlgorithmException, KeyManagementException {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override/*w w w.  j  a v a  2 s .co m*/
        public void checkClientTrusted(X509Certificate[] certs, String authType) {
        }

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

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    } };

    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new SecureRandom());
    return sc;
}

From source file:com.dida.plugin.smslib.org.smslib.modem.IPModemDriver.java

@Override
protected void connectPort() throws GatewayException, IOException, InterruptedException {
    try {//from   ww  w  .  j  a  va 2 s  .  c o m
        Logger.getInstance().logInfo("Opening: " + this.ipAddress + " @" + this.ipPort, null,
                getGateway().getGatewayId());
        this.tc = new TelnetClient();
        this.tc.addOptionHandler(this.ttopt);
        this.tc.addOptionHandler(this.echoopt);
        this.tc.addOptionHandler(this.gaopt);
        if (getGateway().getIpProtocol() == IPProtocols.BINARY) {
            this.tc.addOptionHandler(this.binaryopt); // Make telnet session binary, so ^Z in ATHander.Sendmessage is send raw!
        }
        if (getGateway().getIpEncryption()) {
            try {
                this.tc.setSocketFactory(SSLContext.getInstance("Default").getSocketFactory());
            } catch (NoSuchAlgorithmException e) {
                Logger.getInstance().logError("Unable to find algorithm needed for using SSL", e,
                        getGateway().getGatewayId());
                // TODO: although not supposed to happen, something should be done if it does
            }
        }
        this.tc.connect(this.ipAddress, this.ipPort);
        this.in = this.tc.getInputStream();
        this.out = this.tc.getOutputStream();
        this.peeker = new Peeker();
    } catch (InvalidTelnetOptionException e) {
        throw new GatewayException("Unsupported telnet option for the selected IP connection.");
    }
}

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  ww. j a v  a  2 s . c o  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:com.vtc.basetube.services.volley.ssl.EasySSLSocketFactory.java

private static SSLContext createEasySSLContext(Context context) throws IOException {
    try {/*from   w w  w.  j av  a 2  s . c o m*/
        // Client should authenticate itself with the valid certificate to
        // Server.
        InputStream clientStream = context.getResources().openRawResource(CERTIFICATE_RESOURCE_CLIENT);
        char[] password = "XXXXXXXXXXXXX".toCharArray();

        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        keyStore.load(clientStream, password);

        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, password);

        // Client should also add the CA certificate obtained from server
        // and create TrustManager from it for the client to validate the
        // identity of the server.
        KeyStore trustStore = KeyStore.getInstance("BKS");
        InputStream instream = null;
        instream = context.getResources().openRawResource(CERTIFICATE_RESOURCE_CA);

        try {
            trustStore.load(instream, "XXXXXXXX".toCharArray());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                instream.close();
            } catch (Exception ignore) {
            }
        }

        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
        tmf.init(trustStore);

        // Create an SSLContext that uses our TrustManager & Keystore
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagerFactory.getKeyManagers(), tmf.getTrustManagers(), null);

        return sslContext;
    } catch (Exception e) {
        e.printStackTrace();
        throw new IOException(e.getMessage());
    }
}

From source file:org.xdi.net.SslDefaultHttpClient.java

private SSLSocketFactory newSslSocketFactory() {
    try {/*from  w w w.j a v  a 2  s.  c  o m*/
        TrustManager[] trustManagers = this.trustManagers;
        if (useTrustManager) {
            trustManagers = getTrustManagers();
        }

        KeyManager[] keyManagers = null;
        if (useKeyManager) {
            keyManagers = getKeyManagers();
        }

        SSLContext ctx = SSLContext.getInstance("TLS");

        ctx.init(keyManagers, trustManagers, new SecureRandom());

        // Pass the keystore to the SSLSocketFactory
        SSLSocketFactory sf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        return sf;
    } catch (Exception ex) {
        throw new IllegalArgumentException("Failed to load keystore", ex);
    }

}

From source file:org.eclipse.lyo.oslc4j.bugzilla.utils.BugzillaHttpClient.java

private static SSLContext getTrustingSSLContext() {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }//  ww w  .j a  va  2  s .  c  o m

        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }
    } };

    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        return sc;
    } catch (KeyManagementException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:com.globo.aclapi.client.ClientAclAPI.java

private static ApacheHttpTransport getTransport(int timeout, boolean verifySSL) throws RuntimeException {
    if (verifySSL) {
        return new ApacheHttpTransport(newDefaultHttpClient(SSLSocketFactory.getSocketFactory(),
                getHttpParams(timeout), ProxySelector.getDefault()));

    } else {/*from ww  w . j  ava2  s  .co m*/
        try {
            SSLContext ctx = SSLContext.getInstance("SSL");
            X509TrustManager tm = new X509TrustManager() {
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

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

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

            ctx.init(null, new TrustManager[] { tm }, null);
            SSLSocketFactory ssf = new SSLSocketFactory(ctx);
            return new ApacheHttpTransport(
                    newDefaultHttpClient(ssf, getHttpParams(timeout), ProxySelector.getDefault()));

        } catch (Exception e) {
            throw new RuntimeException("ERRO ssl schema", e);
        }
    }
}

From source file:io.specto.hoverfly.junit.HoverflyRuleUtils.java

static void setHoverflyTrustStore() throws KeyStoreException, CertificateException, NoSuchAlgorithmException,
        IOException, KeyManagementException, URISyntaxException {
    // load your key store as a stream and initialize a KeyStore
    InputStream trustStream = findResourceOnClasspath("hoverfly.jks").toURL().openStream();

    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());

    // load the stream to your store
    trustStore.load(trustStream, "hoverfly".toCharArray());

    // initialize a trust manager factory with the trusted store
    TrustManagerFactory trustFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustFactory.init(trustStore);/*from ww  w  .  ja v  a2s. c om*/

    // get the trust managers from the factory
    TrustManager[] trustManagers = trustFactory.getTrustManagers();

    // initialize an ssl context to use these managers and set as default
    SSLContext sslContext = SSLContext.getInstance("SSL");
    sslContext.init(null, trustManagers, null);
    SSLContext.setDefault(sslContext);
}

From source file:org.springframework.cloud.vault.ClientHttpRequestFactoryFactory.java

private static SSLContext getSSLContext(VaultProperties.Ssl ssl) throws GeneralSecurityException, IOException {

    KeyManager[] keyManagers = ssl.getKeyStore() != null
            ? createKeyManagerFactory(ssl.getKeyStore(), ssl.getKeyStorePassword()).getKeyManagers()
            : null;//from w w  w.  j  av a 2 s .c om

    TrustManager[] trustManagers = ssl.getTrustStore() != null
            ? createTrustManagerFactory(ssl.getTrustStore(), ssl.getTrustStorePassword()).getTrustManagers()
            : null;

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

    return sslContext;
}

From source file:io.github.thefishlive.updater.HttpServer.java

public void run() {
    try {/*  w w  w. j  a  v a  2  s.  c  o m*/
        int port = GitUpdater.port;

        // Set up the HTTP protocol processor
        HttpProcessor httpproc = HttpProcessorBuilder.create().add(new ResponseDate())
                .add(new ResponseServer("GitUpdater/1.0-SNAPSHOT")).add(new ResponseContent())
                .add(new ResponseConnControl()).build();

        // Set up request handlers
        UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper();
        reqistry.register("*", new ResponceHandler());

        // Set up the HTTP service
        HttpService httpService = new HttpService(httpproc, reqistry);

        SSLServerSocketFactory sf = null;
        if (port == 8443) {
            // Initialize SSL context
            ClassLoader cl = getClass().getClassLoader();
            URL url = cl.getResource("my.keystore");
            if (url == null) {
                System.out.println("Keystore not found");
                System.exit(1);
            }
            KeyStore keystore = KeyStore.getInstance("jks");
            keystore.load(url.openStream(), "secret".toCharArray());
            KeyManagerFactory kmfactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmfactory.init(keystore, "secret".toCharArray());
            KeyManager[] keymanagers = kmfactory.getKeyManagers();
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(keymanagers, null, null);
            sf = sslcontext.getServerSocketFactory();
        }

        try {
            Thread t = new RequestListenerThread(port, httpService, sf);
            t.setDaemon(false);
            t.start();
        } catch (BindException ex) {
            System.out.println("Error binding to port " + port);
            System.out.println("Perhaps another server is running on that port");
            return;
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}