Securing Android Apps with SSL Pinning | React Native | Flutter

RoyalBosS
2 min readSep 23, 2024

--

Android Security
Android Security

What is SSL Pinning?

  1. SSL pinning is a technique used to improve the security of network communications in mobile applications.
  2. It ensures that the app only communicates with servers using specific SSL certificates, protecting against attacks like man-in-the-middle (MITM).
  3. The app stores the server’s public key (usually derived from the certificate) and checks the public key presented by the server during communication.

Why SSL Pinning?

  1. Without SSL pinning, a hacker could intercept, modify, or spoof server responses, even if HTTPS is being used.
  2. Protection against Man-in-the-Middle Attacks
  3. Decreases chances of data leak
  4. Enhanced user privacy

Limitations of SSL Pinning

  1. SSL-pinned Android app must be updated whenever the SSL certificate changes, including auto-renewal.

Step-by-Step Implementation

  1. Generating the Certificate’s SHA-256 Hash
openssl s_client -connect example.com:443 </dev/null 2>/dev/null | openssl x509 -noout -pubkey | openssl pkey -pubin -outform DER | openssl dgst -sha256 -binary | openssl base64
# Replace example.com with your domain

2. Pinning SSL Certificate

// SSLPinnerFactory.java
package com.example;

import com.facebook.react.modules.network.OkHttpClientFactory;
import com.facebook.react.modules.network.OkHttpClientProvider;
import okhttp3.CertificatePinner;
import okhttp3.OkHttpClient;

public class SSLPinnerFactory implements OkHttpClientFactory {

public OkHttpClient createNewNetworkModuleClient() {
CertificatePinner certificatePinner = new CertificatePinner.Builder()
.add("example.com", "sha256/********************************************") // Replace example.com with your domain & Paste hash generated in prev step
.add("dev.example.com", "sha256/********************************************")
.build();

OkHttpClient.Builder clientBuilder = OkHttpClientProvider.createClientBuilder();
return clientBuilder
.certificatePinner(certificatePinner)
.build();
}
}

3. Connect SSLPinnerFactory

// MainApplication.java
package com.example;

public class MainApplication extends Application implements ReactApplication {
@Override
public void onCreate() {
super.onCreate();
OkHttpClientProvider.setOkHttpClientFactory(new SSLPinnerFactory()); // Add this line
}
}

That’s It !

--

--