Example usage for javax.net.ssl SSLContext getDefault

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

Introduction

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

Prototype

public static SSLContext getDefault() throws NoSuchAlgorithmException 

Source Link

Document

Returns the default SSL context.

Usage

From source file:org.wso2.carbon.identity.sso.agent.openid.OpenIDManager.java

private ConsumerManager getConsumerManagerInstance() throws SSOAgentException {

    HttpFetcherFactory httpFetcherFactory = null;
    try {//from   www . jav  a  2 s  .  c  o m
        httpFetcherFactory = new HttpFetcherFactory(SSLContext.getDefault(), null);
    } catch (NoSuchAlgorithmException e) {
        throw new SSOAgentException("Error while getting default SSL Context", e);
    }
    return new ConsumerManager(new RealmVerifierFactory(new YadisResolver(httpFetcherFactory)), new Discovery(),
            httpFetcherFactory);
}

From source file:org.bitrepository.protocol.http.HttpsFileExchange.java

@Override
protected HttpClient getHttpClient() {
    HttpClient client = new DefaultHttpClient();
    try {//from  w w  w  .ja  va  2s.  co  m
        SSLSocketFactory socketFactory = new SSLSocketFactory(SSLContext.getDefault());
        Scheme sch = new Scheme("https",
                settings.getReferenceSettings().getFileExchangeSettings().getPort().intValue(), socketFactory);
        client.getConnectionManager().getSchemeRegistry().register(sch);
    } catch (Exception e) {
        throw new IllegalStateException("Could not make Https Client.", e);
    }

    return client;
}

From source file:de.lespace.apprtc.WebSocketChannelClient.java

public WebSocketFactory getFactory(boolean trustAll) {

    // Install the all-trusting trust manager
    try {/*from   w  w w .  j  av  a2  s  .c o  m*/

        SSLContext sslContext = SSLContext.getDefault();
        // Create a WebSocketFactory instance.
        WebSocketFactory factory = new WebSocketFactory();
        // Set the custom SSL context.
        if (trustAll)
            factory.setSSLContext(NaiveSSLContext.getInstance("TLS"));
        else
            factory.setSSLContext(sslContext);

        return factory;
    } catch (Exception e) {
        Log.i(TAG, "SSLContextProblem: " + e.getMessage());
        e.printStackTrace();
        return null;
    }
}

From source file:se.vgregion.incidentreport.pivotaltracker.impl.PivotalTrackerServiceImpl.java

public PivotalTrackerServiceImpl(Properties p) {
    ptUser = p.getProperty(TYCK_TILL_PT_USER_KEY);
    if (ptUser == null || ptUser.trim().length() == 0) {
        throw new RuntimeException("Missing username in pivotalTracker.properties");
    }//from   ww  w  .ja  v  a2s.  c  o  m
    ptPwd = p.getProperty(TYCKTILL_PT_PWD_KEY);
    try {
        sslContext = SSLContext.getDefault();
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.elasticsearch.xpack.security.transport.ssl.SslIntegrationTests.java

public void testThatUnconfiguredCiphersAreRejected() throws Exception {
    Set<String> supportedCiphers = Sets
            .newHashSet(SSLContext.getDefault().getSupportedSSLParameters().getCipherSuites());
    Set<String> defaultXPackCiphers = Sets.newHashSet(XPackSettings.DEFAULT_CIPHERS);
    final List<String> unconfiguredCiphers = new ArrayList<>(
            Sets.difference(supportedCiphers, defaultXPackCiphers));
    Collections.shuffle(unconfiguredCiphers, random());
    assumeFalse("the unconfigured ciphers list is empty", unconfiguredCiphers.isEmpty());

    try (TransportClient transportClient = new TestXPackTransportClient(
            Settings.builder().put(transportClientSettings()).put("node.name", "programmatic_transport_client")
                    .put("cluster.name", internalCluster().getClusterName())
                    .putList("xpack.ssl.cipher_suites", unconfiguredCiphers).build(),
            LocalStateSecurity.class)) {

        TransportAddress transportAddress = randomFrom(
                internalCluster().getInstance(Transport.class).boundAddress().boundAddresses());
        transportClient.addTransportAddress(transportAddress);

        transportClient.admin().cluster().prepareHealth().get();
        fail("Expected NoNodeAvailableException");
    } catch (NoNodeAvailableException e) {
        assertThat(e.getMessage(), containsString("None of the configured nodes are available: [{#transport#"));
    }//www.  j  a v  a 2s . c  o m
}

From source file:org.wso2.carbon.security.tls.CarbonTLSDump.java

/**
 * /*from   w w  w  .  jav a  2  s.  c o m*/
 * @param ctxt
 */
protected void activate(ComponentContext context) {

    try {

        // returns an array containing all the installed providers. the order of the providers in the array is their
        // preference order.
        Provider providers[] = Security.getProviders();

        StringBuilder buffer = new StringBuilder();

        buffer.append(System.lineSeparator());
        buffer.append(System.lineSeparator());
        buffer.append("[The list of crypto providers available in the system]" + System.lineSeparator());
        buffer.append(System.lineSeparator());

        for (int i = 0; i < providers.length; i++) {
            buffer.append((providers[i].getName() + ":" + providers[i].getClass().getName()
                    + System.lineSeparator()));
        }

        // returns the default SSL server socket factory.
        // the first time this method is called, the security property "ssl.ServerSocketFactory.provider" is
        // examined. if it is non-null, a class by that name is loaded and instantiated. if that is successful and
        // the object is an instance of SSLServerSocketFactory, it is made the default SSL server socket factory.
        // otherwise, this method returns SSLContext.getDefault().getServerSocketFactory(). if that call fails, an
        // inoperative factory is returned.
        SSLServerSocketFactory ssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();

        buffer.append(System.lineSeparator());

        buffer.append("[Java Secure Socket Extension (JSSE)]" + System.lineSeparator());
        buffer.append(System.lineSeparator());

        buffer.append("JSSE provider name: " + SSLContext.getDefault().getProvider().getName()
                + System.lineSeparator());
        buffer.append("JSSE provider info: " + SSLContext.getDefault().getProvider().getInfo()
                + System.lineSeparator());
        buffer.append("JSSE implementation class name: "
                + SSLContext.getDefault().getProvider().getClass().getName() + System.lineSeparator());
        buffer.append(System.lineSeparator());

        // returns a copy of the SSLParameters indicating the default settings for this SSL context.
        // the parameters will always have the cipher suites and protocols arrays set to non-null values.
        SSLParameters sslParams = SSLContext.getDefault().getDefaultSSLParameters();

        buffer.append("[Configuration data from catalina-server.xml]" + System.lineSeparator());
        buffer.append(System.lineSeparator());

        buffer.append("Cipher suites configured in the system: " + System.lineSeparator());
        loadFromArray(sslParams.getCipherSuites(), buffer);
        buffer.append(System.lineSeparator());

        buffer.append("TLS/SSL protocols configured in the system: " + System.lineSeparator());
        loadFromArray(sslParams.getProtocols(), buffer);
        buffer.append(System.lineSeparator());

        buffer.append("Client authentication is required ? " + sslParams.getNeedClientAuth()
                + System.lineSeparator());
        buffer.append(
                "Client authentication is optional? " + sslParams.getWantClientAuth() + System.lineSeparator());
        buffer.append(System.lineSeparator());

        buffer.append("[Runtime SSL/TLS details]" + System.lineSeparator());
        buffer.append(System.lineSeparator());

        // returns the names of the cipher suites which could be enabled for use on an SSL connection created by
        // this factory. normally, only a subset of these will actually be enabled by default, since this list may
        // include cipher suites which do not meet quality of service requirements for those defaults. such cipher
        // suites are useful in specialized applications.
        String[] availableCiphers = ssf.getSupportedCipherSuites();

        buffer.append(
                "All available cipher suites from the JSSE provider in the system:" + System.lineSeparator());

        boolean isJdkPatched = false;

        for (int i = 0; i < availableCiphers.length; ++i) {

            if (JAVA_VERSION.equals("1.8")
                    && Java8CipherUtil.TLS_DHE_RSA_WITH_AES_256_GCM_SHA384.equals(availableCiphers[i])) {
                isJdkPatched = true;
            } else if (JAVA_VERSION.equals("1.7")
                    && Java7CipherUtil.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384.equals(availableCiphers[i])) {
                isJdkPatched = true;
            }

            buffer.append("\t" + "\t" + availableCiphers[i] + System.lineSeparator());
        }

        buffer.append(System.lineSeparator());

        // returns the list of cipher suites which are enabled by default. unless a different list is enabled,
        // handshaking on an SSL connection will use one of these cipher suites. The minimum quality of service for
        // these defaults requires confidentiality protection and server authentication (that is, no anonymous
        // cipher suites).
        String[] defaultCiphers = ssf.getDefaultCipherSuites();

        buffer.append("The list of cipher suites functional in the system with the JSSE provider:"
                + System.lineSeparator());

        for (int i = 0; i < defaultCiphers.length; ++i) {
            buffer.append("\t" + "\t" + defaultCiphers[i] + System.lineSeparator());
        }

        buffer.append(System.lineSeparator());

        buffer.append("Is the JDK patched with JCE unlimited strength jurisdiction policy files ? "
                + isJdkPatched + System.lineSeparator());

        log.info(buffer.toString());

    } catch (Throwable e) {
        log.error(e);
    }

}

From source file:de.btobastian.javacord.utils.DiscordWebsocketAdapter.java

private void connect() {
    WebSocketFactory factory = new WebSocketFactory();
    try {//from   w  w  w. ja  v  a2  s . co  m
        factory.setSSLContext(SSLContext.getDefault());
    } catch (NoSuchAlgorithmException e) {
        logger.warn("An error occurred while setting ssl context", e);
    }
    try {
        websocket = factory.createSocket(gateway + "?encoding=json&v=5");
        websocket.addHeader("Accept-Encoding", "gzip");
        websocket.addListener(this);
        websocket.connect();
    } catch (IOException | WebSocketException e) {
        logger.warn("An error occurred while connecting to websocket", e);
    }
}

From source file:at.diamonddogs.net.ssl.CustomSSLSocketFactory.java

/**
 * @see org.apache.http.conn.scheme.SocketFactory#createSocket()
 *//*from  w w  w  . ja  va2s . c  o m*/
@Override
public Socket createSocket() throws IOException {
    if (sslcontext != null) {
        return sslcontext.getSocketFactory().createSocket();
    } else {
        try {
            return SSLContext.getDefault().getSocketFactory().createSocket();
        } catch (Exception e) {
            return null;
        }
    }
}

From source file:org.finra.herd.dao.JestClientFactory.java

/**
 * Builds and returns a JEST client.//www  .java  2  s . co  m
 *
 * @return the configured JEST client
 */
public JestClient getJestClient() {
    // Retrieve the configuration values used for setting up an Elasticsearch JEST client.
    final String esRegionName = configurationHelper
            .getProperty(ConfigurationValue.ELASTICSEARCH_AWS_REGION_NAME);
    final String hostname = configurationHelper
            .getProperty(ConfigurationValue.ELASTICSEARCH_DOMAIN_REST_CLIENT_HOSTNAME);
    final int port = configurationHelper.getProperty(ConfigurationValue.ELASTICSEARCH_DOMAIN_REST_CLIENT_PORT,
            Integer.class);
    final String scheme = configurationHelper
            .getProperty(ConfigurationValue.ELASTICSEARCH_DOMAIN_REST_CLIENT_SCHEME);
    final String serverUri = String.format("%s://%s:%d", scheme, hostname, port);
    final int connectionTimeout = configurationHelper
            .getProperty(ConfigurationValue.ELASTICSEARCH_REST_CLIENT_CONNECTION_TIMEOUT, Integer.class);
    final int readTimeout = configurationHelper
            .getProperty(ConfigurationValue.ELASTICSEARCH_REST_CLIENT_READ_TIMEOUT, Integer.class);

    LOGGER.info("Elasticsearch REST Client Settings:  scheme={}, hostname={}, port={}, serverUri={}", scheme,
            hostname, port, serverUri);

    DefaultAWSCredentialsProviderChain awsCredentialsProvider = new DefaultAWSCredentialsProviderChain();
    final AWSSigner awsSigner = new AWSSigner(awsCredentialsProvider, esRegionName, "es",
            () -> LocalDateTime.now(ZoneOffset.UTC));

    final AWSSigningRequestInterceptor requestInterceptor = new AWSSigningRequestInterceptor(awsSigner);

    JestClientFactoryStaticInner jestClientFactory = new JestClientFactoryStaticInner(requestInterceptor);

    if (StringUtils.equalsIgnoreCase(scheme, "https")) {
        SSLConnectionSocketFactory sslSocketFactory;
        try {
            sslSocketFactory = new SSLConnectionSocketFactory(SSLContext.getDefault(),
                    NoopHostnameVerifier.INSTANCE);
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException(e);
        }

        jestClientFactory.setHttpClientConfig(
                new HttpClientConfig.Builder(serverUri).connTimeout(connectionTimeout).readTimeout(readTimeout)
                        .sslSocketFactory(sslSocketFactory).multiThreaded(true).build());
    } else {
        jestClientFactory.setHttpClientConfig(new HttpClientConfig.Builder(serverUri)
                .connTimeout(connectionTimeout).readTimeout(readTimeout).multiThreaded(true).build());
    }

    return jestClientFactory.getObject();
}

From source file:com.emc.vipr.services.s3.ViPRS3HttpClient.java

public ViPRS3HttpClient(ViPRS3Config viprConfig) {
    super(viprConfig.getClientConfiguration(), new SmartHttpClient(viprConfig.toSmartClientConfig()), null);

    ClientConfiguration azConfig = viprConfig.getClientConfiguration();
    HttpParams httpClientParams = httpClient.getParams();

    HttpConnectionParams.setConnectionTimeout(httpClientParams, azConfig.getConnectionTimeout());
    HttpConnectionParams.setSoTimeout(httpClientParams, azConfig.getSocketTimeout());
    HttpConnectionParams.setStaleCheckingEnabled(httpClientParams, true);
    HttpConnectionParams.setTcpNoDelay(httpClientParams, true);

    int socketSendBufferSizeHint = azConfig.getSocketBufferSizeHints()[0];
    int socketReceiveBufferSizeHint = azConfig.getSocketBufferSizeHints()[1];
    if (socketSendBufferSizeHint > 0 || socketReceiveBufferSizeHint > 0) {
        HttpConnectionParams.setSocketBufferSize(httpClientParams,
                Math.max(socketSendBufferSizeHint, socketReceiveBufferSizeHint));
    }/*from  w  ww.ja va  2s .  com*/

    ClientConnectionManager connectionManager = httpClient.getConnectionManager();
    ((SmartHttpClient) httpClient).setRedirectStrategy(new LocationHeaderNotRequiredRedirectStrategy());

    try {
        Scheme http = new Scheme("http", 80, PlainSocketFactory.getSocketFactory());
        SSLSocketFactory sf = new SSLSocketFactory(SSLContext.getDefault(),
                SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
        Scheme https = new Scheme("https", 443, sf);
        SchemeRegistry sr = connectionManager.getSchemeRegistry();
        sr.register(http);
        sr.register(https);
    } catch (NoSuchAlgorithmException e) {
        throw new AmazonClientException("Unable to access default SSL context", e);
    }

    /*
     * If SSL cert checking for endpoints has been explicitly disabled,
     * register a new scheme for HTTPS that won't cause self-signed certs to
     * error out.
     */
    if (System.getProperty(SDKGlobalConfiguration.DISABLE_CERT_CHECKING_SYSTEM_PROPERTY) != null) {
        Scheme sch = new Scheme("https", 443, new TrustingSocketFactory());
        httpClient.getConnectionManager().getSchemeRegistry().register(sch);
    }

    /* Set proxy if configured */
    String proxyHost = azConfig.getProxyHost();
    int proxyPort = azConfig.getProxyPort();
    if (proxyHost != null && proxyPort > 0) {
        log.info("Configuring Proxy. Proxy Host: " + proxyHost + " " + "Proxy Port: " + proxyPort);
        HttpHost proxyHttpHost = new HttpHost(proxyHost, proxyPort);
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHttpHost);

        String proxyUsername = azConfig.getProxyUsername();
        String proxyPassword = azConfig.getProxyPassword();
        String proxyDomain = azConfig.getProxyDomain();
        String proxyWorkstation = azConfig.getProxyWorkstation();

        if (proxyUsername != null && proxyPassword != null) {
            ((SmartHttpClient) httpClient).getCredentialsProvider().setCredentials(
                    new AuthScope(proxyHost, proxyPort),
                    new NTCredentials(proxyUsername, proxyPassword, proxyWorkstation, proxyDomain));
        }

        // Add a request interceptor that sets up proxy authentication pre-emptively if configured
        if (azConfig.isPreemptiveBasicProxyAuth()) {
            ((SmartHttpClient) httpClient).addRequestInterceptor(new PreemptiveProxyAuth(proxyHttpHost), 0);
        }
    }
}