我正在做一个银行应用程序,用于使用 HTTPs 为安全目的交互客户端和服务器,因为我必须使用 rest 模板在 android 中添加 SSL pinning。我检查了许多链接以获取 restemplate 代码,但它无法正常工作。这对于 Android 中的 SSL 固定是否正确?我在 Google.Developer.android 找到了这段代码
我已经在我的应用程序中添加了 cert 证书,但是如何与 restemplate 连接:
CertificateFactory cf = CertificateFactory.getInstance("X.509");
InputStream is = ctx.getResources().openRawResource(R.raw.cedgenetbankingin); // Place your 'your_cert.crt' file in `res/raw`
InputStream caInput = new BufferedInputStream(is);
Certificate ca;
try {
ca = cf.generateCertificate(caInput);
System.out.println("ca=" + ((X509Certificate) ca).getSubjectDN());
} finally {
caInput.close();
}
// Create a KeyStore containing our trusted CAs
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);
// Create a TrustManager that trusts the CAs in our KeyStore
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
// Create an SSLContext that uses our TrustManager
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, tmf.getTrustManagers(), null);
HostnameVerifier allHostsValid = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
Log.i("JJ","true--");
return true;
}
};
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
注意:添加证书就足够了吗?从原始文件夹中,我添加了 crt 文件。如果我在文件中进行一些更改,我会遇到异常,所以 resttemplate 不会调用。如果文件正确意味着它的工作?
休息模板代码:
RestTemplate restTemplate = new RestTemplate();
// RestTemplate restTemplate = new RestTemplate();
try {
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
HttpHeaders headers = createHttpHeaders();
HttpEntity<String> entity = new HttpEntity<>(str_encodedparams, headers);
ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
System.out.println("Result - status (" + response.getStatusCode() + ") has body: " + response.hasBody());
System.out.println(response.getBody());
respo = response.getBody();
System.out.println(respo);
} catch (Exception eek) {
eek.printStackTrace();
System.out.println("** Exception: " + eek.getMessage());
}