DEV Community

Cover image for Guide to Implementing SSL Pinning in React Native for iOS and Android
Ajmal Hasan
Ajmal Hasan

Posted on

Guide to Implementing SSL Pinning in React Native for iOS and Android

Securing data transmission in mobile applications is critical. One way to secure this communication is through SSL Pinning. SSL Pinning ensures that your app only communicates with your server using trusted certificates, enhancing the security against man-in-the-middle (MITM) attacks.

This guide will walk you through setting up SSL pinning in both iOS and Android in your React Native app.


Gathering Information for SSL Pinning

Step 1: Test Your SSL Certificate

Start by going to the SSL Labs SSL Test, enter your domain or api base url, and initiate a scan. The results will include details about your SSL certificate.

SSL Labs SSL Test Screenshot

Step 2: Requirements for iOS SSL Pinning

Note: iOS requires at least two public key hashes (primary and backup) to enable SSL pinning.

Two Hashes Requirement

Step 3: Copy the SHA256 Pin

Locate and copy the Pin SHA256 hash.

Pin SHA256 Screenshot

Image description

Note:

  1. We can get SHA256 Pin from Additional Certificates (if supplied) also.
  2. Check Valid until on the page. After this the certificate will expire so you again have to add new ones and make new app builds.

Implementing SSL Pinning on iOS

Step 1: Update Your Podfile

Add TrustKit to your Podfile for SSL pinning support.

require_relative '../node_modules/react-native/scripts/react_native_pods'
require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules'
platform :ios, '12.4'
install! 'cocoapods', :deterministic_uuids => false

target 'sslPinning' do
  config = use_native_modules!
  pod 'TrustKit' # Add TrustKit for SSL Pinning
  ...
Enter fullscreen mode Exit fullscreen mode

Run pod install to install the new dependency.

Step 2: Configure AppDelegate.mm

  1. Import TrustKit by adding the following line:
   #import <TrustKit/TrustKit.h>
Enter fullscreen mode Exit fullscreen mode
  1. Configure TrustKit in the application:didFinishLaunchingWithOptions: method.
   - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
   {
...
     NSDictionary *trustKitConfig = @{
       kTSKSwizzleNetworkDelegates: @YES,
       kTSKPinnedDomains: @{
           @"yourdomain.com" : @{
               kTSKIncludeSubdomains: @YES,
               kTSKEnforcePinning: @YES,
               kTSKDisableDefaultReportUri: @YES,
               kTSKPublicKeyHashes : @[
                 @"<Primary SHA256 key>", // Replace with your actual SHA256 key
                 @"<Backup SHA256 key>",  // Replace with a backup key
               ],
           },
       }};
     [TrustKit initSharedInstanceWithConfiguration:trustKitConfig];
...
     RCTAppSetupPrepareApp(application);
Enter fullscreen mode Exit fullscreen mode

Update "yourdomain.com" with your domain and replace <Primary SHA256 key> and <Backup SHA256 key> with your actual SHA256 keys.


Implementing SSL Pinning on Android

a) JAVA

Step 1: Create SSLPinningFactory.java

Inside android/app/src/main/java/com/yourappname/, create a new file named SSLPinningFactory.java and add the following code:

package com.yourappname; // Update with your package name

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

public class SSLPinningFactory implements OkHttpClientFactory {
   private static String hostname = "yourdomain.com"; // Update with your domain

   public OkHttpClient createNewNetworkModuleClient() {

      CertificatePinner certificatePinner = new CertificatePinner.Builder()
        .add(hostname, "sha256/<your SHA256 key>") // Replace with your SHA256 key
        .build();

      OkHttpClient.Builder clientBuilder = OkHttpClientProvider.createClientBuilder();
      return clientBuilder.certificatePinner(certificatePinner).build();
  }
}
Enter fullscreen mode Exit fullscreen mode

Note: Replace "your SHA256 key" with your actual SHA256 hash.

Step 2: Register the SSL Pinning Factory in MainApplication.java

In MainApplication.java, configure SSL Pinning by adding the following line in the onCreate method:

import com.facebook.react.modules.network.OkHttpClientProvider;
...

public class MainApplication extends Application implements ReactApplication {

  @Override
  public void onCreate() {
    super.onCreate();
    ReactFeatureFlags.useTurboModules = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED;
    SoLoader.init(this, /* native exopackage */ false);
    initializeFlipper(this, getReactNativeHost().getReactInstanceManager());

    OkHttpClientProvider.setOkHttpClientFactory(new SSLPinningFactory()); // Register the SSLPinningFactory
  }
}
Enter fullscreen mode Exit fullscreen mode

---------------------OR----------------------

b) KOTLIN

SSLPinningFactory.kt

package com.-----

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

class SSLPinningFactory : OkHttpClientFactory {
    companion object {
        private const val hostname = "-----"
        private val sha256Keys = listOf(
            "sha256/------",
            "sha256/------")
    }
    override fun createNewNetworkModuleClient(): OkHttpClient {
        val certificatePinnerBuilder = CertificatePinner.Builder()
        for (key in sha256Keys) {
            certificatePinnerBuilder.add(hostname, key)
        }
        val certificatePinner = certificatePinnerBuilder.build()
        val clientBuilder = OkHttpClientProvider.createClientBuilder()
        return clientBuilder.certificatePinner(certificatePinner).build()
    }
}
Enter fullscreen mode Exit fullscreen mode

MainApplication.kt

...
import com.facebook.react.modules.network.OkHttpClientProvider // Import OkHttpClientProvider

class MainApplication : Application(), ReactApplication {

...

  override fun onCreate() {
    super.onCreate()
    SoLoader.init(this, false)

    if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) {
      load() // Load native entry point for New Architecture
    }
    ReactNativeFlipper.initializeFlipper(this, reactNativeHost.reactInstanceManager)

    // Register SSLPinningFactory for OkHttpClientProvider
    + OkHttpClientProvider.setOkHttpClientFactory(SSLPinningFactory())
  }
}

Enter fullscreen mode Exit fullscreen mode

Conclusion

That’s it! You’ve successfully implemented SSL pinning for both iOS and Android in your React Native app. This setup ensures that only secure, trusted connections to your server are allowed, protecting your app from potential MITM attacks. 🥳

For more information, refer to the detailed guide from Callstack's SSL Pinning Blog.

Top comments (0)