Android SSL Pinning(防止中间人攻击)

为了防止中间人攻击,我们需要证书固定技术

Android:https://developer.android.com/training/articles/security-ssl.html#Pinning
OKHttp CertificatePinner: https://square.github.io/okhttp/3.x/okhttp/okhttp3/CertificatePinner.html
OKHttp Certificate Pinning: https://square.github.io/okhttp/https/#certificate-pinning-kt-java

通过证书固定的技术,应用可以更好地保护自己免受以欺诈方式发放的证书的攻击。

在OKhttp中实现SSL Pinning是十分简单的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public final class CertificatePinning {
private final OkHttpClient client = new OkHttpClient.Builder()
.certificatePinner(
new CertificatePinner.Builder()
.add("publicobject.com", "sha256/Vjs8r4z+80wjNcr1YKepWQboSIRi63WsWXhIMN+eWys=")
.build())
.build();

public void run() throws Exception {
Request request = new Request.Builder()
.url("https://publicobject.com/robots.txt")
.build();

try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

for (Certificate certificate : response.handshake().peerCertificates()) {
System.out.println(CertificatePinner.pin(certificate));
}
}
}

public static void main(String... args) throws Exception {
new CertificatePinning().run();
}
}

另外从Android 24起,支持SSL Pinning是一件十分简单的事情,在AndroidManifest.xml file中指定`configuration file

1
2
3
4
<application
android:networkSecurityConfig="@xml/network_security_config"
>
</application>
1
2
3
4
5
6
7
8
9
10
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config>
<domain includeSubdomains="true">appmattus.com</domain>
<pin-set>
<pin digest="SHA-256">4hw5tz+scE+TW+mlai5YipDfFWn1dqvfLG+nU7tq1V8=</pin>
<pin digest="SHA-256">YLh1dUR9y6Kja30RrAn7JKnbQG/uEtLMkBgFF2Fuihg=</pin>
</pin-set>
</domain-config>
</network-security-config>

更多集成方式(Retrofit / Picasso / Volley)请参考:Android Security: SSL Pinning

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :