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:edu.washington.iam.tools.IamConnectionManager.java

protected void initSocketFactory() {
    log.debug("sr sock factory init");

    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }//from w ww.j a v a 2  s  . c o  m

        public void checkClientTrusted(X509Certificate[] certs, String authType) {
            return;
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType) {
            return;
        }
    } };

    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        // sc.init(keyManagers, trustManagers, new java.security.SecureRandom());
        sc.init(keyManagers, trustAllCerts, new java.security.SecureRandom());
        // socketFactory = sc.getSocketFactory();
    } catch (Exception e) {
        log.error("mango initSF error: " + e);
    }
}

From source file:com.dongfang.utils.OtherUtils.java

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

            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }

            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        } };
    }
    // Install the all-trusting trust manager
    final SSLContext sslContext;
    try {
        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustAllCerts, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
    } catch (Throwable e) {
        ULog.e(e.getMessage(), e);
    }
    HttpsURLConnection
            .setDefaultHostnameVerifier(org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
}

From source file:org.apache.hadoop.gateway.jetty.JettyHttpsTest.java

@Test
public void testHttps() throws Exception {
    int port = jetty.getConnectors()[0].getLocalPort();
    String url = "https://localhost:" + port + "/";

    System.out.println("Jetty HTTPS listenting on port " + port + ". Press any key to continue.");
    System.in.read();//from  w  ww  .  j  av a  2 s.  com

    SSLContext ctx = SSLContext.getInstance("TLS");
    KeyManager[] keyManagers = createKeyManagers("jks", "target/test-classes/client-keystore.jks", "horton");
    TrustManager[] trustManagers = createTrustManagers("jks", "target/test-classes/client-truststore.jks",
            "horton");
    ctx.init(keyManagers, trustManagers, new SecureRandom());

    SSLSocketFactory socketFactory = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    SchemeRegistry schemes = new SchemeRegistry();
    schemes.register(new Scheme("https", port, socketFactory));
    ClientConnectionManager cm = new BasicClientConnectionManager(schemes);

    HttpClient client = new DefaultHttpClient(cm);

    HttpGet get = new HttpGet(url);
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    client.execute(get).getEntity().writeTo(buffer);
    assertThat(buffer.toString(), equalTo("<html>Hello!</html>"));
}

From source file:io.coala.capability.online.FluentHCOnlineCapability.java

@Override
public void initialize() throws NoSuchAlgorithmException, KeyManagementException {
    synchronized (FluentHCOnlineCapability.class) {
        if (setup)
            return;

        if (!getBinder().inject(ConfiguringCapability.class).getProperty(TRUST_MANAGER_DISABLED_PROPERTY_KEY)
                .getBoolean(TRUST_MANAGER_DISABLED_PROPERTY_DEFAULT))
            return;

        final SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(new KeyManager[0], new TrustManager[] { new DummyTrustManager() }, new SecureRandom());
        SSLContext.setDefault(ctx);
        setup = true;/*from   w  w  w.  j a v a2s .  c  o m*/
    }
}

From source file:edu.vt.middleware.ldap.LdapTLSSocketFactory.java

/**
 * Creates the underlying SSLContext using truststore and keystore attributes
 * and makes this factory ready for use. Must be called before factory can be
 * used./*  w w w  .  jav  a  2 s .c o m*/
 *
 * @throws  IOException  if the keystore cannot be loaded
 * @throws  GeneralSecurityException  if the SSLContext cannot be created
 */
public void initialize() throws IOException, GeneralSecurityException {
    final SSLContext ctx = SSLContext.getInstance(DEFAULT_PROTOCOL);
    final TrustManager[] tm = this.initTrustManager(this.getTrustStoreStream(), this.getTrustStorePassword(),
            this.getTrustStoreType());
    final KeyManager[] km = this.initKeyManager(this.getKeyStoreStream(), this.getKeyStorePassword(),
            this.getKeyStoreType());
    ctx.init(km, tm, null);
    this.factory = ctx.getSocketFactory();
}

From source file:edu.kit.dama.rest.util.auth.impl.BearerTokenAuthenticator.java

@Override
public IAuthorizationContext obtainAuthorizationContext(HttpContext hc, GroupId groupId)
        throws UnauthorizedAccessAttemptException {
    String token = hc.getRequest().getHeaderValue("Authorization");//getQueryParameters().getFirst("authToken");
    if (token == null) {
        throw new UnauthorizedAccessAttemptException("No authorization header entry provided.");
    }//w  w w.j  a v a2 s  .  c o  m
    if (token.startsWith("Bearer ")) {
        LOGGER.debug("Starting bearer token authentication.");
        if (tokenInfoServiceUrl != null) {
            LOGGER.debug("Validating provided bearer token using info service at '{}'.", tokenInfoServiceUrl);
            //if validate, do this
            ClientConfig config = new DefaultClientConfig();

            try {
                SSLContext ctx = SSLContext.getInstance("TLS");
                ctx.init(null, new TrustManager[] { TRUST_MANAGER }, new SecureRandom());

                config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
                        new HTTPSProperties(VERIFIER, ctx));
                com.sun.jersey.api.client.Client client = com.sun.jersey.api.client.Client.create(config);
                WebResource webResource = client.resource(new URL(tokenInfoServiceUrl).toURI());
                String result = webResource.header("Authorization", token).get(String.class);
                LOGGER.debug("Service returned result {}. Checking 'exp' property.", result);
                JSONObject resultObject = new JSONObject(result);

                long expiresAt = resultObject.getLong("exp");
                LOGGER.debug("Token exp property is set to value {}.", expiresAt);
                if (System.currentTimeMillis() > expiresAt) {
                    throw new UnauthorizedAccessAttemptException(
                            "The provided bearer token has expired at timestamp " + expiresAt + ".");
                }
            } catch (NoSuchAlgorithmException | KeyManagementException ex) {
                throw new UnauthorizedAccessAttemptException(
                        "Failed to perform secured access to token info service.", ex);
            } catch (MalformedURLException | URISyntaxException ex) {
                throw new UnauthorizedAccessAttemptException(
                        "Failed to access token info service due to a malformed URL.", ex);
            }
        }
        //still valid or not checked...remove 'Bearer ' part and continue
        LOGGER.debug("Token validation succeeded/skipped. Proceeding with authentication");
        token = token.replaceFirst("Bearer ", "");
    } else {
        throw new UnauthorizedAccessAttemptException(
                "No bearer token provided in authorization header. Token is '" + token + "'");
    }

    IMetaDataManager manager = MetaDataManagement.getMetaDataManagement().getMetaDataManager();
    manager.setAuthorizationContext(AuthorizationContext.factorySystemContext());
    try {
        String tokenKey = CryptUtil.stringToSHA1(token);
        LOGGER.debug("Obtaining service access token for key {}", tokenKey);
        ServiceAccessToken accessToken = ServiceAccessUtil.getAccessToken(manager, tokenKey,
                getAuthenticatorId());

        if (accessToken == null) {
            throw new UnauthorizedAccessAttemptException("No access token obtained for tokenKey '" + tokenKey
                    + "' and serviceId '" + getAuthenticatorId() + "'");
        }
        LOGGER.debug("Building and returning AuthorizationContext for user {}", accessToken.getUserId());
        //no secret handling needed for the moment as only the token is validated
        return buildAuthorizationContext(new UserId(accessToken.getUserId()), groupId);
    } catch (UnauthorizedAccessAttemptException | EntityNotFoundException ex) {
        throw new UnauthorizedAccessAttemptException(
                "The access using the provided HttpContext has not been authorized.", ex);
    } finally {
        manager.close();
    }
}

From source file:es.tid.fiware.rss.oauth.service.OauthManager.java

/**
 * Read needed properties from file./*from   ww  w.  j a  v a  2 s.  c o  m*/
 */
@PostConstruct
private void readProperties() throws Exception {
    externalLogin = oauthProperties.getProperty("config.externalLogin");
    baseSite = oauthProperties.getProperty("config.baseUrl");
    clientId = oauthProperties.getProperty("config.client_id");
    clientSecret = oauthProperties.getProperty("config.client_secret");
    authorizeUrl = oauthProperties.getProperty("config.authorizeUrl");
    accessTokenUrl = oauthProperties.getProperty("config.accessTokenUrl");
    callbackURL = oauthProperties.getProperty("config.callbackURL");
    userInfoUrl = oauthProperties.getProperty("config.userInfoUrl");
    grantedRole = oauthProperties.getProperty("config.grantedRole");
    getApplicationsUrl = oauthProperties.getProperty("config.getApplications");
    useOauth = oauthProperties.getProperty("config.useOauth");
    // avoid certificate checking for problems regarding with them.
    SSLContext ctx = SSLContext.getInstance("TLS");
    X509TrustManager tm = new X509TrustManager() {
        @Override
        public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    };
    ctx.init(null, new TrustManager[] { tm }, null);
    SSLSocketFactory ssf = new SSLSocketFactory(ctx);
    ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    httpclient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", ssf, 443));
}

From source file:fr.wseduc.webdav.WebDav.java

private Sardine getSardine(String uri, Message<JsonObject> message) {
    String host;/*from ww  w . j  a va2 s  . c  om*/
    try {
        host = new URI(uri).getHost();
    } catch (URISyntaxException e) {
        sendError(message, e.getMessage(), e);
        return null;
    }
    JsonObject credential = credentials.getJsonObject(host);
    Sardine sardine;
    if (credential != null) {
        if (credential.getBoolean("insecure", false)) {
            sardine = new SardineImpl() {
                @Override
                protected ConnectionSocketFactory createDefaultSecureSocketFactory() {
                    SSLConnectionSocketFactory sf = null;
                    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

                        @Override
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                            return null;
                        }

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

                        @Override
                        public void checkServerTrusted(java.security.cert.X509Certificate[] certs,
                                String authType) {
                        }
                    } };
                    try {
                        SSLContext context = SSLContext.getInstance("TLS");
                        context.init(null, trustAllCerts, null);

                        sf = new SSLConnectionSocketFactory(context,
                                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
                    } catch (NoSuchAlgorithmException | KeyManagementException e) {
                        logger.error(e.getMessage(), e);
                    }
                    return sf;
                }
            };
            sardine.setCredentials(credential.getString("username"), credential.getString("password"));
        } else {
            sardine = SardineFactory.begin(credential.getString("username"), credential.getString("password"));
        }
        sardine.enablePreemptiveAuthentication(host);
    } else {
        sardine = SardineFactory.begin();
    }
    return sardine;
}

From source file:org.appenders.log4j2.elasticsearch.jest.PEMCertInfo.java

@Override
public void applyTo(HttpClientConfig.Builder builder) {

    if (java.security.Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
        java.security.Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    }/*from w  ww . j a  v  a 2 s .  c  o m*/

    try (FileInputStream clientCert = new FileInputStream(new File(clientCertPath));
            FileInputStream key = new FileInputStream(new File(keyPath));
            FileInputStream certificateAuthoritiies = new FileInputStream(new File(caPath))) {
        KeyStore keyStore = PemReader.loadKeyStore(clientCert, key, Optional.ofNullable(keyPassphrase));
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, keyPassphrase.toCharArray());

        KeyStore trustStore = PemReader.loadTrustStore(certificateAuthoritiies);

        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);

        // TODO: add support for hostname verification modes
        builder.sslSocketFactory(new SSLConnectionSocketFactory(sslContext));
        builder.httpsIOSessionStrategy(new SSLIOSessionStrategy(sslContext, new NoopHostnameVerifier()));

    } catch (IOException | GeneralSecurityException e) {
        throw new ConfigurationException(configExceptionMessage, e);
    }

}

From source file:immf.MyWiser.java

private SSLSocketFactory createSslSocketFactory(String keystoreFile, String keyType, String keypasswd) {
    InputStream keyis = null;/*from w ww .j  a  v a 2  s  . c o m*/
    try {
        keyis = new FileInputStream(keystoreFile);
        KeyStore keyStore = KeyStore.getInstance(keyType);
        keyStore.load(keyis, keypasswd.toCharArray());

        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(keyStore, keypasswd.toCharArray());

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

        context.init(kmf.getKeyManagers(), null, new SecureRandom());
        return context.getSocketFactory();
    } catch (Exception e) {
        e.printStackTrace();
        return (SSLSocketFactory) SSLSocketFactory.getDefault();
    } finally {
        try {
            keyis.close();
        } catch (Exception e) {
        }
    }
}