I'm doing a banking application for interacting client and server for secure purpose using HTTPs for that I have to add SSL pinning in android using rest template. I checked many links for restemplate code, but it's not working properly. Is this correct or not for SSL pinning in android? I found this code at Google.Developer.android
I have added the cert certificate in my application, but how to connect with 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());
Note: for adding the certificate is enough right? From raw folder I added the crt file. If I make some changes in the file I'm getting exception so resttemplate doesn't call. If the file is correct means its working?
Resttemplate code:
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());
}