To add SSL pinning in a Kotlin
Android app, follow these step-by-step instructions:
Step 1: Add the OkHttp library to your project.
Add the OkHttp dependency to your app-level build.gradle
file:
implementation 'com.squareup.okhttp3:okhttp:4.9.1'
Step 2: Create a Certificate Pinning Helper class.
Create a new Kotlin class in your project, e.g., CertificatePinningHelper
. This class will contain the logic for SSL pinning. Here's a basic implementation:
import okhttp3.CertificatePinner
object CertificatePinningHelper {
private const val HOSTNAME = "your-api-hostname.com"
private const val PIN = "sha256/YourPublicKeyHash"
fun getCertificatePinner(): CertificatePinner {
return CertificatePinner.Builder()
.add(HOSTNAME, PIN)
.build()
}
}
Replace your-api-hostname.com with the actual hostname of the API you want to pin certificates for. Replace YourPublicKeyHash with the actual public key hash of the server certificate. You can obtain the public key hash using OpenSSL or other similar tools.
Step 3: Initialize OkHttpClient with CertificatePinner.
In your networking code, create an instance of OkHttpClient and configure it to use the CertificatePinner created in the previous step. Here's an example:
import okhttp3.OkHttpClient
val client = OkHttpClient.Builder()
.certificatePinner(CertificatePinningHelper.getCertificatePinner())
.build()
Step 4: Use the OkHttpClient for network requests.
Use the configured OkHttpClient instance for making network requests. For example:
import okhttp3.Request
val request = Request.Builder()
.url("https://your-api-hostname.com/api/endpoint")
.build()
client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
// Handle network request failure
}
override fun onResponse(call: Call, response: Response) {
// Handle network response
}
})
Make sure to replace https://your-api-hostname.com/api/endpoint
with the actual API endpoint you want to access.
That's it! With these steps, you have added SSL pinning to your Kotlin Android app using OkHttp.