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:net.atos.aeon.AEONSDK.java

private void Init(String subscribeUrl, String id, String desc) {

    this.messages = new AEONSDKMessages();

    try {//from w  ww  .  j  av  a 2s.com
        if (subscribeUrl.indexOf("/subscribe") != -1) {
            if (subscribeUrl.startsWith("https")) {

                this.webClient = ClientHelper.createClient();

                SSLContext sc = SSLContext.getInstance("TLS");
                sc.init(null, ClientHelper.trustAllCerts, new SecureRandom());
                SocketIO.setDefaultSSLSocketFactory(sc);
                HttpsURLConnection.setDefaultHostnameVerifier(new RelaxedHostNameVerifier());

            } else
                this.webClient = Client.create();

            this.subscribeUrl = subscribeUrl;
            this.socketServer = getSocketServerEndpoint(getServerEndpoint(subscribeUrl));

            this.socket = new SocketIO(socketServer);
            this.socket.addHeader("force_new_connection", "true");
            // this.socket.addHeader("transports", "xhr-polling");
            // this.socket.addHeader("polling duration", "20");

            this.id = id;
            this.desc = desc;
            this.mode = "subscribe";
            sioLogger.setLevel(Level.OFF);
        } else
            this.mode = "error";
    } catch (MalformedURLException e) {
        e.printStackTrace();
        this.mode = "error";
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        this.mode = "error";
    } catch (KeyManagementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        this.mode = "error";
    }

}

From source file:com.gravspace.core.HttpServer.java

public static void start(String[] args) throws Exception {

    int port = 8082;
    if (args.length >= 1) {
        port = Integer.parseInt(args[0]);
    }//from  ww w. ja  va 2  s.co m

    ActorSystem system = ActorSystem.create("Application-System");
    Properties config = new Properties();
    config.load(HttpServer.class.getResourceAsStream("/megapode.conf"));
    ActorRef master = system.actorOf(Props.create(CoordinatingActor.class, config), "Coordinator");

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

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

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

    SSLServerSocketFactory sf = null;
    if (port == 8443) {
        // Initialize SSL context
        ClassLoader cl = HttpServer.class.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();
    }

    RequestListenerThread t = new RequestListenerThread(port, httpService, sf);
    t.setDaemon(false);
    t.start();

    t.join();
}

From source file:com.apporiented.hermesftp.utils.SecurityUtil.java

/**
 * Create the security context required for SSL communication.
 * /*w  w  w.  jav a2s  .c o m*/
 * @param keyStoreFile The name of the keystore file.
 * @param keyStorePassword The password for the keystore.
 * @return The context.
 * @throws FtpConfigException Thrown on error in configuration.
 */
public static SSLContext createSslContext(String keyStoreFile, char[] keyStorePassword)
        throws FtpConfigException {
    SSLContext sslContext;
    try {
        /* Get keystore file and password */
        InputStream ksInputStream = getKeyStoreInputStream(keyStoreFile);

        /*
         * Get the java keystore object an key manager. A keystore is where keys and
         * certificates are kept.
         */
        KeyStore keystore = KeyStore.getInstance("JKS");
        keystore.load(ksInputStream, keyStorePassword);
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(keystore, keyStorePassword);

        /*
         * An SSLContext is an environment for implementing JSSE. It is used to create a
         * ServerSocketFactory
         */
        sslContext = SSLContext.getInstance("SSL");
        sslContext.init(kmf.getKeyManagers(), null, null);
    } catch (KeyManagementException e) {

        throw new SecurityException("A key management authorization problem occurred.");
    } catch (FileNotFoundException e) {
        throw new SecurityException("The key store file could not be found.");
    } catch (KeyStoreException e) {
        throw new SecurityException("A key store problem occurred.");
    } catch (NoSuchAlgorithmException e) {
        throw new SecurityException("The hash algorithm is not supported.");
    } catch (CertificateException e) {
        throw new SecurityException("Certificate could not be loaded.");
    } catch (UnrecoverableKeyException e) {
        throw new SecurityException("Key store cannot be recovered.");
    } catch (IOException e) {
        throw new SecurityException("Reading the key store failed.");
    }
    return sslContext;
}

From source file:org.jclouds.http.httpnio.pool.NioHttpCommandConnectionPool.java

public static IOEventDispatch provideSSLClientEventDispatch(AsyncNHttpClientHandler handler, HttpParams params)
        throws NoSuchAlgorithmException, KeyManagementException {
    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, null, null);/*from   w  w  w.j  a  v a2  s.  co m*/
    return new SSLClientIOEventDispatch(handler, context, params);
}

From source file:org.sickbeard.SickBeard.java

public SickBeard(String hostname, String port, String api, boolean https, String extraPath, String user,
        String password, boolean trustAll, String trustMe) {
    this.hostname = hostname;
    this.port = port;
    this.extraPath = "/" + extraPath + "/";
    this.path = this.extraPath + "/api/" + api + "/";
    try {//from  w ww .j  ava  2s .c o m
        this.https = https;
        this.scheme = https ? "https" : "http";

        Authenticator.setDefault(new SickAuthenticator(user, password, hostname));
        HostnameVerifier verifier;
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager(trustAll, trustMe) },
                new SecureRandom());
        if (trustAll) {
            verifier = new AllowAllHostnameVerifier();
        } else {
            verifier = new StrictHostnameVerifier();
        }
        HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(verifier);
    } catch (Exception e) {
        ;
    }
    /***********************************************************
     * ANDROID SPECIFIC START                                  *
     ***********************************************************/
    // start a AsyncTask to try and find the actual api version number
    AsyncTask<Void, Void, CommandsJson> task = new AsyncTask<Void, Void, CommandsJson>() {
        @Override
        protected CommandsJson doInBackground(Void... arg0) {
            try {
                return SickBeard.this.sbGetCommands();
            } catch (Exception e) {
                Log.e("SickBeard", e.getMessage(), e);
                return null;
            }
        }

        @Override
        protected void onPostExecute(CommandsJson result) {
            // do nothing because this is a network error
            if (result == null)
                return;
            try {
                // if we get a version use it
                SickBeard.this.apiVersion = Integer.valueOf(result.api_version);
            } catch (NumberFormatException e) {
                // 2 was the odd float so assume its 2 if we cant get an int
                SickBeard.this.apiVersion = 2;
            }
        }
    };
    task.execute();
    /***********************************************************
     * ANDROID SPECIFIC END                                    *
     ***********************************************************/
}

From source file:com.youTransactor.uCube.mdm.MDMManager.java

public void initialize(Context context) {
    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);

    onSharedPreferenceChanged(settings, null);

    settings.registerOnSharedPreferenceChangeListener(this);

    try {//ww  w .j  a v  a2 s.co  m
        KeyStore keystoreCA = KeyStore.getInstance(KEYSTORE_TYPE);
        keystoreCA.load(context.getResources().openRawResource(R.raw.keystore), PWD);

        KeyStore keystoreClient = null;

        File file = context.getFileStreamPath(KEYSTORE_CLIENT_FILENAME);

        if (file.exists()) {
            keystoreClient = KeyStore.getInstance(KEYSTORE_TYPE);
            InputStream in = new FileInputStream(file);
            keystoreClient.load(in, PWD);
        }

        ready = keystoreClient != null && keystoreClient.getKey(MDM_CLIENT_CERT_ALIAS, PWD) != null;

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(keystoreCA);

        KeyManagerFactory kmf = KeyManagerFactory.getInstance("X509");
        kmf.init(keystoreClient, PWD);

        sslContext = SSLContext.getInstance("TLS");

        sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

    } catch (Exception e) {
        LogManager.debug(MDMManager.class.getSimpleName(), "load keystore error", e);
    }
}

From source file:com.example.mp_master.helper.UntrustedSSLSocketFactory.java

/**
 * Creates the default SSL socket factory.
 * This constructor is used exclusively to instantiate the factory for
 * {@link #getSocketFactory getSocketFactory}.
 * @throws NoSuchAlgorithmException /*from w  w w .j a va 2 s  . co  m*/
 * @throws KeyManagementException 
 */
private UntrustedSSLSocketFactory() {
    super();
    this.nameResolver = null;
    TrustManager[] blindTrustMan = new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(X509Certificate[] c, String a) throws CertificateException {
        }

        public void checkServerTrusted(X509Certificate[] c, String a) throws CertificateException {
        }
    } };
    SSLContext sl = null;
    SSLSocketFactory sslf = null;
    try {
        sl = SSLContext.getInstance(TLS);
        sl.init(null, blindTrustMan, new java.security.SecureRandom());
        sslf = sl.getSocketFactory();
    } catch (Exception e) {
        e.printStackTrace();
        sslf = HttpsURLConnection.getDefaultSSLSocketFactory();
    }

    this.sslcontext = sl;
    this.socketfactory = sslf;

}

From source file:com.tune.reporting.base.service.TuneServiceProxy.java

/**
 * Post request to TUNE Service API Service
 *
 * @return Boolean True if successful posting request, else False.
 * @throws TuneSdkException If error within SDK.
 *///ww w. j  a v a 2  s  . c  o m
protected boolean postRequest() throws TuneSdkException {
    URL url = null;
    HttpsURLConnection conn = null;

    try {
        url = new URL(this.uri);
    } catch (MalformedURLException ex) {
        throw new TuneSdkException(String.format("Problems executing request: %s: %s: '%s'", this.uri,
                ex.getClass().toString(), ex.getMessage()), ex);
    }

    try {
        // connect to the server over HTTPS and submit the payload
        conn = (HttpsURLConnection) url.openConnection();

        // Create the SSL connection
        SSLContext sc;
        sc = SSLContext.getInstance("TLS");
        sc.init(null, null, new java.security.SecureRandom());
        conn.setSSLSocketFactory(sc.getSocketFactory());

        conn.setRequestMethod("GET");
        conn.setUseCaches(false);
        conn.setAllowUserInteraction(false);
        conn.connect();

        // Gets the status code from an HTTP response message.
        final int responseHttpCode = conn.getResponseCode();

        // Returns an unmodifiable Map of the header fields.
        // The Map keys are Strings that represent the response-header
        // field names. Each Map value is an unmodifiable List of Strings
        // that represents the corresponding field values.
        final Map<String, List<String>> responseHeaders = conn.getHeaderFields();

        final String requestUrl = url.toString();

        // Gets the HTTP response message, if any, returned along
        // with the response code from a server.
        String responseRaw = conn.getResponseMessage();

        // Pull entire JSON raw response
        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line + "\n");
        }
        br.close();

        responseRaw = sb.toString();

        // decode to JSON
        JSONObject responseJson = new JSONObject(responseRaw);

        this.response = new TuneServiceResponse(responseRaw, responseJson, responseHttpCode, responseHeaders,
                requestUrl.toString());
    } catch (Exception ex) {
        throw new TuneSdkException(String.format("Problems executing request: %s: '%s'",
                ex.getClass().toString(), ex.getMessage()), ex);
    }

    return true;
}

From source file:com.pipinan.githubcrawler.GithubCrawler.java

/**
 * Just to avoid the ssl exception when using HttpClient to access https url
 *
 * @return/*from   w  w  w  . j a  v  a 2 s.c o m*/
 */
private HttpClient getHttpClient() {
    try {
        SSLContext sslContext = SSLContext.getInstance("SSL");

        sslContext.init(null, new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

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

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

        SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext,
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpClient httpClient = HttpClientBuilder.create().setSSLSocketFactory(socketFactory).build();

        return httpClient;

    } catch (Exception e) {
        e.printStackTrace();
        return HttpClientBuilder.create().build();
    }
}

From source file:com.appdynamics.openstack.nova.RestClient.java

static HttpClient httpClientWithTrustManager() throws KeyManagementException, NoSuchAlgorithmException {
    HttpClient httpClient = new DefaultHttpClient();

    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout);

    httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, timeout);

    httpClient.getParams().setParameter("http.connection-manager.max-per-host", 1);

    X509TrustManager tm = new X509TrustManager() {

        @Override/*from ww w  .  j  a v  a 2 s. co m*/
        public X509Certificate[] getAcceptedIssuers() {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // TODO Auto-generated method stub

        }

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // TODO Auto-generated method stub

        }
    };

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

    ctx.init(null, new TrustManager[] { tm }, null);

    SSLSocketFactory ssf = new SSLSocketFactory(ctx);

    ClientConnectionManager ccm = httpClient.getConnectionManager();

    SchemeRegistry sr = ccm.getSchemeRegistry();

    sr.register(new Scheme("https", ssf, 443)); // Scheme("https", ssf, 443));

    return new DefaultHttpClient(ccm, httpClient.getParams());

}