Skip to content

Instantly share code, notes, and snippets.

@samueljmurray
Last active August 26, 2021 08:22
Show Gist options
  • Save samueljmurray/ab4309e9e9866c419620f935e601eb0f to your computer and use it in GitHub Desktop.
Save samueljmurray/ab4309e9e9866c419620f935e601eb0f to your computer and use it in GitHub Desktop.
Certificate pinning in React Native Android
package com.example.app;
import com.facebook.react.modules.network.OkHttpClientFactory;
import com.facebook.react.modules.network.OkHttpClientProvider;
import com.facebook.react.modules.network.ReactCookieJarContainer;
import java.util.concurrent.TimeUnit;
import okhttp3.CertificatePinner;
import okhttp3.OkHttpClient;
public class OkHttpCertPin implements OkHttpClientFactory {
private static String hostname = "*.your.service.com";
@Override
public OkHttpClient createNewNetworkModuleClient() {
CertificatePinner certificatePinner = new CertificatePinner.Builder()
.add(hostname, "sha256/YOUR_PUBLIC_KEY_HASH")
.add(hostname, "sha256/YOUR_PUBLIC_KEY_HASH_BACKUP1")
.add(hostname, "sha256/YOUR_PUBLIC_KEY_HASH_BACKUP2")
.build();
OkHttpClient.Builder client = new OkHttpClient.Builder()
.connectTimeout(0, TimeUnit.MILLISECONDS)
.readTimeout(0, TimeUnit.MILLISECONDS)
.writeTimeout(0, TimeUnit.MILLISECONDS)
.cookieJar(new ReactCookieJarContainer())
.certificatePinner(certificatePinner);
return OkHttpClientProvider.enableTls12OnPreLollipop(client).build();
}
}
@threesquared
Copy link

This method does not seem to work with react-native 0.44.0. The client is replaced successfully but making a XMLHttpRequest to a pinned URL inside the JS completes successfully when the pins are not correct.

However after replacing the client the following java code does result in a javax.net.ssl.SSLPeerUnverifiedException being thrown.

Request request = new Request.Builder().url("https://domain.com/test").build();
Response response = OkHttpClientProvider.getOkHttpClient().newCall(request).execute();

@samueljmurray
Copy link
Author

I've updated this so it should work with react-native 0.54.0 and later

@CorentinGC
Copy link

CorentinGC commented Feb 17, 2020

Hi !
I try to implement this on my react-native app (0.61) but I can't get it working. There is no build error, and with bad certificate I can access my API.

Is it still working on last react-native release?

Thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment