Search in sources :

Example 41 with SSLSocketFactory

use of javax.net.ssl.SSLSocketFactory in project Talon-for-Twitter by klinker24.

the class GetLocations method getJsonResponse.

public static String getJsonResponse() {
    String json = "";
    try {
        String oauth_token = "";
        String oauth_token_secret = "";
        // generate authorization header
        String get_or_post = "GET";
        String oauth_signature_method = "HMAC-SHA1";
        String uuid_string = UUID.randomUUID().toString();
        uuid_string = uuid_string.replaceAll("-", "");
        // any relatively random alphanumeric string will work here
        String oauth_nonce = uuid_string;
        // get the timestamp
        Calendar tempcal = Calendar.getInstance();
        // get current time in milliseconds
        long ts = tempcal.getTimeInMillis();
        // then divide by 1000 to get seconds
        String oauth_timestamp = (new Long(ts / 1000)).toString();
        // the parameter string must be in alphabetical order, "text" parameter added at end
        String parameter_string = "oauth_consumer_key=" + "" + "&oauth_nonce=" + oauth_nonce + "&oauth_signature_method=" + oauth_signature_method + "&oauth_timestamp=" + oauth_timestamp + "&oauth_token=" + encode(oauth_token) + "&oauth_version=1.0";
        String twitter_endpoint = "https://api.twitter.com/1.1/trends/available.json";
        String twitter_endpoint_host = "api.twitter.com";
        String twitter_endpoint_path = "/1.1/trends/available.json";
        String signature_base_string = get_or_post + "&" + encode(twitter_endpoint) + "&" + encode(parameter_string);
        String oauth_signature = computeSignature(signature_base_string, "" + "&" + encode(oauth_token_secret));
        String authorization_header_string = "OAuth oauth_consumer_key=\"" + "V9yijGrKf79jlYi0l3ekpA" + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"" + oauth_timestamp + "\",oauth_nonce=\"" + oauth_nonce + "\",oauth_version=\"1.0\",oauth_signature=\"" + encode(oauth_signature) + "\",oauth_token=\"" + encode(oauth_token) + "\"";
        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, "UTF-8");
        HttpProtocolParams.setUserAgent(params, "HttpCore/1.1");
        HttpProtocolParams.setUseExpectContinue(params, false);
        HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { // Required protocol interceptors
        new RequestContent(), new RequestTargetHost(), // Recommended protocol interceptors
        new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() });
        HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
        HttpContext context = new BasicHttpContext(null);
        HttpHost host = new HttpHost(twitter_endpoint_host, 443);
        DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
        context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
        context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);
        SSLContext sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(null, null, null);
        SSLSocketFactory ssf = sslcontext.getSocketFactory();
        Socket socket = ssf.createSocket();
        socket.connect(new InetSocketAddress(host.getHostName(), host.getPort()), 0);
        conn.bind(socket, params);
        BasicHttpEntityEnclosingRequest request2 = new BasicHttpEntityEnclosingRequest("GET", twitter_endpoint_path);
        request2.setParams(params);
        request2.addHeader("Authorization", authorization_header_string);
        httpexecutor.preProcess(request2, httpproc, context);
        HttpResponse response2 = httpexecutor.execute(request2, conn, context);
        response2.setParams(params);
        httpexecutor.postProcess(response2, httpproc, context);
        json = EntityUtils.toString(response2.getEntity());
        conn.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return json;
}
Also used : InetSocketAddress(java.net.InetSocketAddress) HttpHost(org.apache.http.HttpHost) BasicHttpParams(org.apache.http.params.BasicHttpParams) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) BasicHttpEntityEnclosingRequest(org.apache.http.message.BasicHttpEntityEnclosingRequest) HttpResponse(org.apache.http.HttpResponse) DefaultHttpClientConnection(org.apache.http.impl.DefaultHttpClientConnection) SSLContext(javax.net.ssl.SSLContext) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) BasicHttpParams(org.apache.http.params.BasicHttpParams) HttpParams(org.apache.http.params.HttpParams) Socket(java.net.Socket)

Example 42 with SSLSocketFactory

use of javax.net.ssl.SSLSocketFactory in project okhttp by square.

the class RealConnection method connectTls.

private void connectTls(ConnectionSpecSelector connectionSpecSelector) throws IOException {
    Address address = route.address();
    SSLSocketFactory sslSocketFactory = address.sslSocketFactory();
    boolean success = false;
    SSLSocket sslSocket = null;
    try {
        // Create the wrapper over the connected socket.
        sslSocket = (SSLSocket) sslSocketFactory.createSocket(rawSocket, address.url().host(), address.url().port(), true);
        // Configure the socket's ciphers, TLS versions, and extensions.
        ConnectionSpec connectionSpec = connectionSpecSelector.configureSecureSocket(sslSocket);
        if (connectionSpec.supportsTlsExtensions()) {
            Platform.get().configureTlsExtensions(sslSocket, address.url().host(), address.protocols());
        }
        // Force handshake. This can throw!
        sslSocket.startHandshake();
        Handshake unverifiedHandshake = Handshake.get(sslSocket.getSession());
        // Verify that the socket's certificates are acceptable for the target host.
        if (!address.hostnameVerifier().verify(address.url().host(), sslSocket.getSession())) {
            X509Certificate cert = (X509Certificate) unverifiedHandshake.peerCertificates().get(0);
            throw new SSLPeerUnverifiedException("Hostname " + address.url().host() + " not verified:" + "\n    certificate: " + CertificatePinner.pin(cert) + "\n    DN: " + cert.getSubjectDN().getName() + "\n    subjectAltNames: " + OkHostnameVerifier.allSubjectAltNames(cert));
        }
        // Check that the certificate pinner is satisfied by the certificates presented.
        address.certificatePinner().check(address.url().host(), unverifiedHandshake.peerCertificates());
        // Success! Save the handshake and the ALPN protocol.
        String maybeProtocol = connectionSpec.supportsTlsExtensions() ? Platform.get().getSelectedProtocol(sslSocket) : null;
        socket = sslSocket;
        source = Okio.buffer(Okio.source(socket));
        sink = Okio.buffer(Okio.sink(socket));
        handshake = unverifiedHandshake;
        protocol = maybeProtocol != null ? Protocol.get(maybeProtocol) : Protocol.HTTP_1_1;
        success = true;
    } catch (AssertionError e) {
        if (Util.isAndroidGetsocknameError(e))
            throw new IOException(e);
        throw e;
    } finally {
        if (sslSocket != null) {
            Platform.get().afterHandshake(sslSocket);
        }
        if (!success) {
            closeQuietly(sslSocket);
        }
    }
}
Also used : Address(okhttp3.Address) ConnectionSpec(okhttp3.ConnectionSpec) SSLSocket(javax.net.ssl.SSLSocket) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) IOException(java.io.IOException) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) X509Certificate(java.security.cert.X509Certificate) Handshake(okhttp3.Handshake)

Example 43 with SSLSocketFactory

use of javax.net.ssl.SSLSocketFactory in project okhttp by square.

the class MockWebServer method processHandshakeFailure.

private void processHandshakeFailure(Socket raw) throws Exception {
    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, new TrustManager[] { UNTRUSTED_TRUST_MANAGER }, new SecureRandom());
    SSLSocketFactory sslSocketFactory = context.getSocketFactory();
    SSLSocket socket = (SSLSocket) sslSocketFactory.createSocket(raw, raw.getInetAddress().getHostAddress(), raw.getPort(), true);
    try {
        // we're testing a handshake failure
        socket.startHandshake();
        throw new AssertionError();
    } catch (IOException expected) {
    }
    socket.close();
}
Also used : SSLSocket(javax.net.ssl.SSLSocket) SecureRandom(java.security.SecureRandom) SSLContext(javax.net.ssl.SSLContext) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) SSLSocketFactory(javax.net.ssl.SSLSocketFactory)

Example 44 with SSLSocketFactory

use of javax.net.ssl.SSLSocketFactory in project okhttp by square.

the class OkHttpAsync method prepare.

@Override
public void prepare(final Benchmark benchmark) {
    concurrencyLevel = benchmark.concurrencyLevel;
    targetBacklog = benchmark.targetBacklog;
    client = new OkHttpClient.Builder().protocols(benchmark.protocols).dispatcher(new Dispatcher(new ThreadPoolExecutor(benchmark.concurrencyLevel, benchmark.concurrencyLevel, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()))).build();
    if (benchmark.tls) {
        SslClient sslClient = SslClient.localhost();
        SSLSocketFactory socketFactory = sslClient.socketFactory;
        HostnameVerifier hostnameVerifier = new HostnameVerifier() {

            @Override
            public boolean verify(String s, SSLSession session) {
                return true;
            }
        };
        client = client.newBuilder().sslSocketFactory(socketFactory, sslClient.trustManager).hostnameVerifier(hostnameVerifier).build();
    }
    callback = new Callback() {

        @Override
        public void onFailure(Call call, IOException e) {
            System.out.println("Failed: " + e);
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            ResponseBody body = response.body();
            long total = SynchronousHttpClient.readAllAndClose(body.byteStream());
            long finish = System.nanoTime();
            if (VERBOSE) {
                long start = (Long) response.request().tag();
                System.out.printf("Transferred % 8d bytes in %4d ms%n", total, TimeUnit.NANOSECONDS.toMillis(finish - start));
            }
            requestsInFlight.decrementAndGet();
        }
    };
}
Also used : Call(okhttp3.Call) SslClient(okhttp3.internal.tls.SslClient) SSLSession(javax.net.ssl.SSLSession) IOException(java.io.IOException) Dispatcher(okhttp3.Dispatcher) HostnameVerifier(javax.net.ssl.HostnameVerifier) ResponseBody(okhttp3.ResponseBody) Response(okhttp3.Response) Callback(okhttp3.Callback) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) SSLSocketFactory(javax.net.ssl.SSLSocketFactory)

Example 45 with SSLSocketFactory

use of javax.net.ssl.SSLSocketFactory in project okhttp by square.

the class ClientAuthTest method clientAuthForWants.

@Test
public void clientAuthForWants() throws Exception {
    OkHttpClient client = buildClient(clientCert, clientIntermediateCa);
    SSLSocketFactory socketFactory = buildServerSslSocketFactory(ClientAuth.WANTS);
    server.useHttps(socketFactory, false);
    server.enqueue(new MockResponse().setBody("abc"));
    Call call = client.newCall(new Request.Builder().url(server.url("/")).build());
    Response response = call.execute();
    assertEquals(new X500Principal("CN=localhost"), response.handshake().peerPrincipal());
    assertEquals(new X500Principal("CN=Jethro Willis"), response.handshake().localPrincipal());
    assertEquals("abc", response.body().string());
}
Also used : Response(okhttp3.Response) MockResponse(okhttp3.mockwebserver.MockResponse) MockResponse(okhttp3.mockwebserver.MockResponse) Call(okhttp3.Call) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) X500Principal(javax.security.auth.x500.X500Principal) DelegatingSSLSocketFactory(okhttp3.DelegatingSSLSocketFactory) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) Test(org.junit.Test)

Aggregations

SSLSocketFactory (javax.net.ssl.SSLSocketFactory)191 SSLSocket (javax.net.ssl.SSLSocket)69 SSLContext (javax.net.ssl.SSLContext)57 IOException (java.io.IOException)45 Socket (java.net.Socket)37 Test (org.junit.Test)33 HttpsURLConnection (javax.net.ssl.HttpsURLConnection)29 HostnameVerifier (javax.net.ssl.HostnameVerifier)27 URL (java.net.URL)23 KeyManagementException (java.security.KeyManagementException)20 OutputStream (java.io.OutputStream)19 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)19 InputStream (java.io.InputStream)18 CertificateException (java.security.cert.CertificateException)17 HttpURLConnection (java.net.HttpURLConnection)15 InetSocketAddress (java.net.InetSocketAddress)15 X509TrustManager (javax.net.ssl.X509TrustManager)15 OkHttpClient (okhttp3.OkHttpClient)14 SSLParameters (javax.net.ssl.SSLParameters)13 TrustManager (javax.net.ssl.TrustManager)13