2016-11-02 60 views

回答

2

OkHttp documentation爲我們提供了一個清晰的方法來完成此示例代碼。如果它消失,在這裏它被粘貼在下面:

1.添加一個破碎的CertificatePinner並提出請求。 任何請求都會執行,即使它不存在。您可以在您的Android應用程序中執行此操作,或者只是創建一個虛擬Java應用程序並運行它。

例如,引腳https://publicobject.com,開始帶着一顆破碎的 配置:

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(); 

正如預期的那樣,這個失敗的證書釘扎例外:

javax.net.ssl.SSLPeerUnverifiedException: Certificate pinning failure! 
    Peer certificate chain: 
    sha256/afwiKY3RxoMmLkuRW1l7QsPZTJPwDS2pdDROQjXw8ig=: CN=publicobject.com, OU=PositiveSSL 
    sha256/klO23nT2ehFDXCfx3eHTDRESMz3asj1muO+4aIdjiuY=: CN=COMODO RSA Secure Server CA 
    sha256/grX4Ta9HpZx6tSHkmCrvpApTQGo67CYDnvprLg5yRME=: CN=COMODO RSA Certification Authority 
    sha256/lCppFqbkrlJ3EcVFAkeip0+44VaoJUymbnOaEUk7tEU=: CN=AddTrust External CA Root 
    Pinned certificates for publicobject.com: 
    sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= 
    at okhttp3.CertificatePinner.check(CertificatePinner.java) 
    at okhttp3.Connection.upgradeToTls(Connection.java) 
    at okhttp3.Connection.connect(Connection.java) 
    at okhttp3.Connection.connectAndSetOwner(Connection.java) 

2.配置您的OkHttp客戶端正確:

CertificatePinner certificatePinner = new CertificatePinner.Builder() 
    .add("publicobject.com", "sha256/afwiKY3RxoMmLkuRW1l7QsPZTJPwDS2pdDROQjXw8ig=") 
    .add("publicobject.com", "sha256/klO23nT2ehFDXCfx3eHTDRESMz3asj1muO+4aIdjiuY=") 
    .add("publicobject.com", "sha256/grX4Ta9HpZx6tSHkmCrvpApTQGo67CYDnvprLg5yRME=") 
    .add("publicobject.com", "sha256/lCppFqbkrlJ3EcVFAkeip0+44VaoJUymbnOaEUk7tEU=") 
    .build(); 

這就是它的全部!

此方法將爲您提供整個鏈中的所有證書。這是有利的,因爲它更安全,因爲鏈中只有一個證書必須匹配請求才能成功。很可能在未來的某個時間點,您的證書將被更新,但只要整個鏈不更新,您的應用程序就不會中斷。