Last active
September 22, 2020 16:09
-
-
Save sergiocasero/88834d5189d7014497522d8358773239 to your computer and use it in GitHub Desktop.
Simple snippet that demonstrates how to make https request with SSL pinning by using ktor on Android
This file contains 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
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) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you want to generate a
bks
file fromjks
one, please, execute the following command: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