Last active
May 25, 2020 07:57
-
-
Save jinal90/3eadf93dec934d61c4a946cceeaedb0f to your computer and use it in GitHub Desktop.
Code snippet to demonstrate implementation of network calls and SSL pinning using TrustStore and SSL socket factory in Android
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// get the TrustStore that you just placed in resources | |
val resourceStream = resources.openRawResource(R.raw.your_trust_store) | |
// create an empty default KeyStore | |
val keyStoreType = KeyStore.getDefaultType() | |
val keyStore = KeyStore.getInstance(keyStoreType) | |
// load the KeyStore from input stream of TrustStore | |
keyStore.load(resourceStream, getTrustStorePassword()?.toCharArray()) | |
val trustManagerAlgorithm = TrustManagerFactory.getDefaultAlgorithm() | |
val trustManagerFactory = TrustManagerFactory.getInstance(trustManagerAlgorithm) | |
trustManagerFactory.init(keyStore) | |
val sslContext = SSLContext.getInstance("TLS") | |
sslContext.init(null, trustManagerFactory.trustManagers, null) | |
// open connection using HttpsURLConnection | |
val urlConnection = url.openConnection() as HttpsURLConnection | |
// assign to sslSocketFactory | |
urlConnection.sslSocketFactory = sslContext.socketFactory | |
// fetch and print the responce | |
val inputStream: InputStream = urlConnection.inputStream | |
var line: String? | |
var sb = StringBuffer() | |
try { | |
BufferedReader(InputStreamReader(inputStream, "UTF-8")).use { br -> | |
while (br.readLine().also { line = it } != null) { | |
sb.append(line) | |
} | |
Log.d("TrustStoreExample", "Response body is " + sb.toString()) | |
} | |
} catch (e: IOException) { | |
Log.d("TrustStoreExample", "Exception occurred " + e.stackTrace) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment