Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Simple snippet that demonstrates how to make https request with SSL pinning by using ktor on Android
class AndroidRemote(private val context: Context) : Remote {
companion object {
private const val SSL_PROTOCOL = "TLSv1.2"
private const val KEYSTORE_PROTOCOL = "BKS"
private const val KEY_MANAGER_ALG = "X509"
private const val KEYSTORE_PATH = "YOUR_ASSET_NAME.bks"
private val KEYSTORE_PASSWORD = "YOUR_PASS".toCharArray() // Find better place to store this please hahaha
private const val API_ENDPOINT = "API_ENDPOINT"
private val sslContext by lazy {
.apply {
val fis =
val keystore = KeyStore.getInstance(KEYSTORE_PROTOCOL)
keystore.load(fis, KEYSTORE_PASSWORD)
val manager = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
val kmf: KeyManagerFactory = KeyManagerFactory.getInstance(KEY_MANAGER_ALG)
kmf.init(keystore, KEYSTORE_PASSWORD)
val random = SecureRandom()
init(kmf.keyManagers, manager.trustManagers, random)
private fun buildClient() = HttpClient(Android.config {
sslManager = { conn -> conn.sslSocketFactory = sslContext.socketFactory }
}) {
defaultRequest {
val urlBuilder = URLBuilder(API_ENDPOINT)
url {
protocol = urlBuilder.protocol
host =
// Just an example, obviously we should get the response and handle it
override suspend fun testSslPinning(phone: String): Either<Error, Success> {
try {
buildClient().use { it.get<String> { url { encodedPath = "path" } } }
return Either.Right(Success)
} catch (e: Exception) {
return Either.Left(Error.Default)
Copy link

sergiocasero commented Sep 22, 2020

If you want to generate a bks file from jks one, please, execute the following command:

keytool -importkeystore -srckeystore YOUR_KEYSTORE.jks -destkeystore YOUR_KEYSTORE.bks -srcstoretype JKS -deststoretype BKS -srcstorepass KEYSTORE_PASS -deststorepass KEYSTORE_PASS -provider org.bouncycastle.jce.provider.BouncyCastleProvider --providerpath "bcprov-jdk16-1.46.jar"

You will need the bcprov library ( and move the JAR to the jks-located folder

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment