Skip to content

Instantly share code, notes, and snippets.

@addam01
Created February 25, 2016 04:27
Show Gist options
  • Save addam01/db1cb34e6ffe8f6e9e2a to your computer and use it in GitHub Desktop.
Save addam01/db1cb34e6ffe8f6e9e2a to your computer and use it in GitHub Desktop.
Android Custom SSL Connection with Self signed Cert
/*Create a certificate factory based on X509 standard, this hold the algorithm for most certs*/
CertificateFactory cf = CertificateFactory.getInstance("X.509");
/*Get the .pem cert from cert file stored in \app\src\main\res\raw*/
InputStream caInput = mContext.getResources().openRawResource(R.raw.cert);
/*Then generate the raw file into certification file*/
Certificate ca = cf.generateCertificate(caInput);
/*Close the inputstream. This is important!*/
caInput.close();
/*Generate the KeyStore, DO NOT USE "BKS". Just use the default type!*/
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
/*Load the default keystore with no parameters*/
keyStore.load(null, null);
/*Assign the certification factory to the KeyStore*/
keyStore.setCertificateEntry("ca", ca);
/*Create an comfigure algorithm using default Trustmanager based algorithm (RSA)*/
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
/*Get the TrustManagerFactory to implement the KeyStore*/
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
/*Assign the SSLContext for the Protocol of the SSL server, in this case TLSv1.2*/
Log.d("Protocol 0", "Assigning SSLContext");
SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
/*Append it with the TrustManagerFactory that holds the KeyStore which holds the Cert*/
sslContext.init(null, tmf.getTrustManagers(), null);
Log.d("Protocol 0", "Assigning SSLSocket Manager");
/* This one uses ION library for AsyncTask */
AsyncSSLSocketMiddleware sslMiddleWare = Ion.getDefault(mContext).getHttpClient().getSSLSocketMiddleware();
sslMiddleWare.setSSLContext(sslContext);
sslMiddleWare.setTrustManagers(tmf.getTrustManagers());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment