Home | History | Annotate | Download | only in recipes
      1 /*
      2  * Copyright (C) 2014 Square, Inc.
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 package com.squareup.okhttp.recipes;
     17 
     18 import com.squareup.okhttp.CertificatePinner;
     19 import com.squareup.okhttp.Interceptor;
     20 import com.squareup.okhttp.OkHttpClient;
     21 import com.squareup.okhttp.Request;
     22 import com.squareup.okhttp.Response;
     23 import java.io.IOException;
     24 import java.security.cert.Certificate;
     25 import java.util.Collections;
     26 import java.util.Set;
     27 
     28 public final class CheckHandshake {
     29   /** Rejects otherwise-trusted certificates. */
     30   private static final Interceptor CHECK_HANDSHAKE_INTERCEPTOR = new Interceptor() {
     31     Set<String> blacklist = Collections.singleton("sha1/DmxUShsZuNiqPQsX2Oi9uv2sCnw=");
     32 
     33     @Override public Response intercept(Chain chain) throws IOException {
     34       for (Certificate certificate : chain.connection().getHandshake().peerCertificates()) {
     35         String pin = CertificatePinner.pin(certificate);
     36         if (blacklist.contains(pin)) {
     37           throw new IOException("Blacklisted peer certificate: " + pin);
     38         }
     39       }
     40       return chain.proceed(chain.request());
     41     }
     42   };
     43 
     44   private final OkHttpClient client = new OkHttpClient();
     45 
     46   public CheckHandshake() {
     47     client.networkInterceptors().add(CHECK_HANDSHAKE_INTERCEPTOR);
     48   }
     49 
     50   public void run() throws Exception {
     51     Request request = new Request.Builder()
     52         .url("https://publicobject.com/helloworld.txt")
     53         .build();
     54 
     55     Response response = client.newCall(request).execute();
     56     if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
     57 
     58     System.out.println(response.body().string());
     59   }
     60 
     61   public static void main(String... args) throws Exception {
     62     new CheckHandshake().run();
     63   }
     64 }
     65