In my situation when I run programm on emulator - its work correktly. But when I install apk to phone - have error Not trusted server certificate. What is the problem?
This is what helped me to build a proper working http communication over ssl.
http://blog.antoine.li/2010/10/22/android-trusting-ssl-certificates/
If you want client (android device) really (not blindly) trusts host, public certificate needs to be loaded to device's KeyStore, otherwise device won't talk to the server
You will use .crt file but to use with Android KeyStore you need it to be converted to "bks". I do following:
// read .crt file from memory
InputStream inStream = ctx.openFileInput("cetificate.crt");
//InputStream inStream = ctx.getAssets().open("wm_loaner.cer");
if(inStream != null)
{
KeyStore cert = CertUtils.ConvertCerToBKS(inStream, "MyAlias", "password".toCharArray());
inStream.close();
}
public static KeyStore ConvertCerToBKS(InputStream cerStream, String alias, char [] password)
{
KeyStore keyStore = null;
try
{
keyStore = KeyStore.getInstance("BKS", "BC");
CertificateFactory factory = CertificateFactory.getInstance("X.509", "BC");
Certificate certificate = factory.generateCertificate(cerStream);
keyStore.load(null, password);
keyStore.setCertificateEntry(alias, certificate);
}
catch ....
{
}
return keyStore;
}
After certificate was converted and loaded to the KeyStore you can establish a connection
You can override certificate of webserver by using addSLLCertificateToHttpRequest()
method. Call addSLLCertificateToHttpRequest()
method before communicating with your server. This will avoid certificate invalidation and always return true. I am writing this method. This is working for me
/**
* The server has a SSL certificate. This method add SSL certificate to HTTP
* Request
*/
public static void addSLLCertificateToHttpRequest() {
// Code to use verifier which return true.
try {
SSLContext sslctx = null;
try {
sslctx = SSLContext.getInstance("TLS");
sslctx.init(null, new TrustManager[] { new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain, String authType)
{
}
public void checkServerTrusted(X509Certificate[] chain, String authType)
{
}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[] {};
}
} }, null);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
HttpsURLConnection.setDefaultSSLSocketFactory(sslctx.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
} catch (Exception e) {
e.printStackTrace();
}
}