下面是一个使用公共证书库来实现SSL Pinning的Android代码示例:
// 导入需要的库
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.conn.ssl.SSLSocketFactory;
public class CustomSSLSocketFactory extends SSLSocketFactory {
private SSLContext sslContext = SSLContext.getInstance("TLS");
public CustomSSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException,
KeyManagementException, KeyStoreException, UnrecoverableKeyException {
super(truststore);
TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
// 检查服务器证书
if (chain == null || chain.length == 0) {
throw new CertificateException("Server certificate is null or empty.");
}
String expectedServerName = "your.server.name.com"; // 期望的服务器名
String certificateServerName = chain[0].getSubjectDN().getName();
if (!certificateServerName.contains(expectedServerName)) {
throw new CertificateException("Certificate is not for the expected server.");
}
}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
};
sslContext.init(null, new TrustManager[] {tm}, null);
}
public CustomSSLSocketFactory(SSLContext context) {
super(context);
sslContext = context;
}
@Override
public Socket createSocket(Socket socket, String host, int port, boolean autoClose)
throws IOException, UnknownHostException {
// 创建新的socket连接
return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
}
@Override
public Socket createSocket() throws IOException {
// 创建新的socket连接
return sslContext.getSocketFactory().createSocket();
}
}
在调用HTTP请求之前,需要为请求对象添加一个定制的SSLSocket工厂类,如下所示:
// 导入需要的库
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
public class MyHttpClient {
public static HttpClient getHttpClient() {
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, null);
SSLSocketFactory sf = new CustomSSLSocketFactory(trustStore); // 将定制的SSLSocket工厂添加到请求中
sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, 3000);
HttpConnectionParams.setSoTimeout(params, 5000);
return new DefaultHttpClient(params);
} catch (Exception e) {
return new DefaultHttpClient();
}
}
public static String getHttpResponse(String url) {
try {
HttpClient httpclient = getHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response = httpclient.execute(httpget);
// 处理HTTP响应
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String result = convertStreamToString(instream);
instream.close();
return result;
}
} else {
Log.e("MyHttpClient", "Http status code: " + statusCode);
}
} catch (ParseException e) {
Log.e("MyHttpClient", e.getMessage());
} catch (IOException e) {
Log.e("MyHttpClient", e.getMessage());
}
return null;
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
Log.e("MyHttpClient", e.getMessage());
} finally {
try {
is.close();
} catch (IOException e) {
Log.e("MyHttpClient", e.getMessage());
}
}
return sb.toString();
}
}
调用时只需使用MyHttpClient.getHttpResponse(url)即可。