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.OkHttpClient; 20 import com.squareup.okhttp.Request; 21 import com.squareup.okhttp.Response; 22 import java.io.IOException; 23 import java.security.cert.Certificate; 24 25 public final class CertificatePinning { 26 private final OkHttpClient client; 27 28 public CertificatePinning() { 29 client = new OkHttpClient(); 30 client.setCertificatePinner( 31 new CertificatePinner.Builder() 32 .add("publicobject.com", "sha1/DmxUShsZuNiqPQsX2Oi9uv2sCnw=") 33 .add("publicobject.com", "sha1/SXxoaOSEzPC6BgGmxAt/EAcsajw=") 34 .add("publicobject.com", "sha1/blhOM3W9V/bVQhsWAcLYwPU6n24=") 35 .add("publicobject.com", "sha1/T5x9IXmcrQ7YuQxXnxoCmeeQ84c=") 36 .build()); 37 } 38 39 public void run() throws Exception { 40 Request request = new Request.Builder() 41 .url("https://publicobject.com/robots.txt") 42 .build(); 43 44 Response response = client.newCall(request).execute(); 45 if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); 46 47 for (Certificate certificate : response.handshake().peerCertificates()) { 48 System.out.println(CertificatePinner.pin(certificate)); 49 } 50 } 51 52 public static void main(String... args) throws Exception { 53 new CertificatePinning().run(); 54 } 55 } 56