0

Hi there I am trying to implement certificate pinning using HttpOk: https://square.github.io/okhttp/3.x/okhttp/okhttp3/CertificatePinner.html

Can anyone give me an idea of where I am meant to put the following code in order to get the certificate pinning exception?

 String hostname = "publicobject.com";
 CertificatePinner certificatePinner = new CertificatePinner.Builder()
     .add(hostname, "sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=")
     .build();
 OkHttpClient client = OkHttpClient.Builder()
     .certificatePinner(certificatePinner)
     .build();

 Request request = new Request.Builder()
     .url("https://" + hostname)
     .build();
 client.newCall(request).execute();

Thanks :)

teiiluj
  • 241
  • 3
  • 10

2 Answers2

0

It is supposed to go wherever you are creating client for your web service calls. Remember you have to replace there public key with your server's public key.

LoveForDroid
  • 1,072
  • 12
  • 25
  • This gives me a: android.os.NetworkOnMainThreadException error. Do you know what I'm doing wrong? – teiiluj Oct 05 '16 at 21:19
  • You are not supposed to run network calls on main thread. You are supposed to run this code in some background task. This error is very well explained in this link: http://stackoverflow.com/questions/6343166/how-to-fix-android-os-networkonmainthreadexception – LoveForDroid Oct 05 '16 at 21:29
0

You should add it whereever you are currently building an OkHttpClient. Specifically the only lines you should be adding to the existing code is

 CertificatePinner certificatePinner = new CertificatePinner.Builder()
     .add(hostname, "sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=")
     .build();

 ...builder.certificatePinner(certificatePinner)...

The NetworkOnMainThreadException is probably because you are also making a call at this point. You don't want to make an additional HTTP call, you just want this applied to all existing calls hitting publicobject.com

If you are on a Mac you can test with oksocial

$ brew install yschimke/tap/oksocial
$ oksocial --certificatePin publicobject.com:sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA  https://publicobject.com/robots.txt
request failed
javax.net.ssl.SSLPeerUnverifiedException: Certificate pinning failure!
  Peer certificate chain:
    sha256/afwiKY3RxoMmLkuRW1l7QsPZTJPwDS2pdDROQjXw8ig=: CN=publicobject.com, OU=PositiveSSL, OU=Domain Control Validated
    sha256/klO23nT2ehFDXCfx3eHTDRESMz3asj1muO+4aIdjiuY=: CN=COMODO RSA Domain Validation Secure Server CA, O=COMODO CA Limited, L=Salford, ST=Greater Manchester, C=GB
    sha256/grX4Ta9HpZx6tSHkmCrvpApTQGo67CYDnvprLg5yRME=: CN=COMODO RSA Certification Authority, O=COMODO CA Limited, L=Salford, ST=Greater Manchester, C=GB
  Pinned certificates for publicobject.com:
    sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=
    at okhttp3.CertificatePinner.check(CertificatePinner.java:187)
Yuri Schimke
  • 12,435
  • 3
  • 35
  • 69