Reputation: 357
I am making a TV application which requests m3u8 file via HTTPS. When I run it on Android 4.4, I see some "handshake failed" in logcat. I suspect it is related to SSL validation problems. May I know how to ignore these errors?
I see there are method like writing my own HTTPSTrustManager by extending X509TrustManager. But the code is in JAVA. My application is in Kotlin. I am new to Android development. May anyone please help me on this?
Thanks.
Upvotes: 2
Views: 3764
Reputation: 738
you can use a self signed certificate using the Volley
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RequestQueue rq = Volley.newRequestQueue(this, new HurlStack(null, getSocketFactory()));
StringRequest s = new StringRequest(Request.Method.GET, "https://192.168.1.10:443",
new Response.Listener<String>() {
@Override
public void onResponse(String s) {
Log.e("RESULT",s);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
Log.e("RESULTfailder",volleyError.getMessage()); }
} );
rq.add(s);
}
private SSLSocketFactory getSocketFactory() {
CertificateFactory cf = null;
try {
cf = CertificateFactory.getInstance("X.509");
InputStream caInput = getResources().openRawResource(R.raw.server);
Certificate ca;
try {
ca = cf.generateCertificate(caInput);
Log.e("CERT", "ca=" + ((X509Certificate) ca).getSubjectDN());
} finally {
caInput.close();
}
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
HostnameVerifier hostnameVerifier = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
Log.e("CipherUsed", session.getCipherSuite());
return hostname.compareTo("192.168.1.10")==0; //The Hostname of your server
}
};
HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
SSLContext context = null;
context = SSLContext.getInstance("TLS");
context.init(null, tmf.getTrustManagers(), null);
HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
SSLSocketFactory sf = context.getSocketFactory();
return sf;
} catch (CertificateException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
return null;
}
}
Upvotes: 1