Securing Android Apps with SSL Pinning | React Native | Flutter
What is SSL Pinning?
- SSL pinning is a technique used to improve the security of network communications in mobile applications.
- It ensures that the app only communicates with servers using specific SSL certificates, protecting against attacks like man-in-the-middle (MITM).
- 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?
- Without SSL pinning, a hacker could intercept, modify, or spoof server responses, even if HTTPS is being used.
- Protection against Man-in-the-Middle Attacks
- Decreases chances of data leak
- Enhanced user privacy
Limitations of SSL Pinning
- SSL-pinned Android app must be updated whenever the SSL certificate changes, including auto-renewal.
Step-by-Step Implementation
- 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
}
}