Skip to content

Instantly share code, notes, and snippets.

@sergiocasero
Last active September 22, 2020 16:09
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
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 {
SSLContext.getInstance(SSL_PROTOCOL)
.apply {
val fis = context.assets.open(KEYSTORE_PATH)
val keystore = KeyStore.getInstance(KEYSTORE_PROTOCOL)
keystore.load(fis, KEYSTORE_PASSWORD)
val manager = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
manager.init(keystore)
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 = urlBuilder.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)
}
}
}
@sergiocasero
Copy link
Author

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 (https://mvnrepository.com/artifact/org.bouncycastle/bcprov-jdk16/1.46) 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