Skip to main content
Redhat Developers  Logo
  • Products

    Platforms

    • Red Hat Enterprise Linux
      Red Hat Enterprise Linux Icon
    • Red Hat AI
      Red Hat AI
    • Red Hat OpenShift
      Openshift icon
    • Red Hat Ansible Automation Platform
      Ansible icon
    • View All Red Hat Products

    Featured

    • Red Hat build of OpenJDK
    • Red Hat Developer Hub
    • Red Hat JBoss Enterprise Application Platform
    • Red Hat OpenShift Dev Spaces
    • Red Hat OpenShift Local
    • Red Hat Developer Sandbox

      Try Red Hat products and technologies without setup or configuration fees for 30 days with this shared Openshift and Kubernetes cluster.
    • Try at no cost
  • Technologies

    Featured

    • AI/ML
      AI/ML Icon
    • Linux
      Linux Icon
    • Kubernetes
      Cloud icon
    • Automation
      Automation Icon showing arrows moving in a circle around a gear
    • View All Technologies
    • Programming Languages & Frameworks

      • Java
      • Python
      • JavaScript
    • System Design & Architecture

      • Red Hat architecture and design patterns
      • Microservices
      • Event-Driven Architecture
      • Databases
    • Developer Productivity

      • Developer productivity
      • Developer Tools
      • GitOps
    • Automated Data Processing

      • AI/ML
      • Data Science
      • Apache Kafka on Kubernetes
    • Platform Engineering

      • DevOps
      • DevSecOps
      • Ansible automation for applications and services
    • Secure Development & Architectures

      • Security
      • Secure coding
  • Learn

    Featured

    • Kubernetes & Cloud Native
      Openshift icon
    • Linux
      Rhel icon
    • Automation
      Ansible cloud icon
    • AI/ML
      AI/ML Icon
    • View All Learning Resources

    E-Books

    • GitOps Cookbook
    • Podman in Action
    • Kubernetes Operators
    • The Path to GitOps
    • View All E-books

    Cheat Sheets

    • Linux Commands
    • Bash Commands
    • Git
    • systemd Commands
    • View All Cheat Sheets

    Documentation

    • Product Documentation
    • API Catalog
    • Legacy Documentation
  • Developer Sandbox

    Developer Sandbox

    • Access Red Hat’s products and technologies without setup or configuration, and start developing quicker than ever before with our new, no-cost sandbox environments.
    • Explore Developer Sandbox

    Featured Developer Sandbox activities

    • Get started with your Developer Sandbox
    • OpenShift virtualization and application modernization using the Developer Sandbox
    • Explore all Developer Sandbox activities

    Ready to start developing apps?

    • Try at no cost
  • Blog
  • Events
  • Videos

Android SPKI Pinning with TrustKit

October 26, 2017
Tom Jackman
Related topics:
Security

Share:

    Introduction

    In this blog post, I will demonstrate how to perform SPKI (Subject Public Key Info) Pinning in an Android Application using TrustKit - a pinning library for Android.

    Pinning Approaches

    One of the most common approaches for pinning in a mobile app is to store the certificate in storage. However, when server certificates are rotated, a new update to the application would likely need to be pushed out since the certificate in the application is no longer valid, possibly preventing use of the app. As rotation is a reoccurring process, it's cumbersome to pin the whole certificate in the app.

    However, since the key pair used to generate certificates are usually the same, you can simply pin the SPKI Fingerprint of the x509 certificate instead. This approach will allow you to still perform pinning without the maintenance of having to push out new application updates when the certificates expire. Another advantage of using this approach is the anonymization of the certificate information as it's being cloaked by a one-way hash function.

    Pinning in Android N

    Starting with Android N (API 24), there is a simplified way to specify pin sets in XML with a Network Security Configuration file. In this file, you can specify the domains you want to pin against. The pins should be defined as a Base64 encoded SPKI Fingerprint.

    <network-security-config>
     <domain includeSubdomains="true">google.com</domain>
      <pin-set>
       <pin digest="SHA-256">GYK+80ic2IxHxZ+KYREJBTEZSmb90DyBKsn0UXOJ1EA=</pin>
      </pin-set>
     </domain-config>
    </network-security-config>

    Pinning with TrustKit

    TrustKit is an Open Source library that provides the key benefit of allowing Android N style pinning to work on lower API levels. TrustKit supports Android N style pinning with API Level 17 and higher.

    Installing

    To add the TrustKit library to your project, reference the TrustKit library in your build.gradle file.

    dependencies {
        compile 'com.datatheorem.android.trustkit:trustkit:1.0.1@aar'
    }

    Configuration

    Create an XML file to hold your configuration under res/xml/network_security_config.xml.

    <?xml version="1.0" encoding="utf-8"?>
    <network-security-config>
        <domain-config cleartextTrafficPermitted="false">
            <domain includeSubdomains="true">google.com</domain>
            <pin-set>
                <pin digest="SHA-256">GYK+80ic2IxHxZ+KYREJBTEZSmb90DyBKsn0UXOJ1EA=</pin>             
                <pin digest="SHA-256">XAoDAV3WG9IKcu0YJ1ZVTuEVqdcglfiQRqmfy3+ieoc=</pin>
            </pin-set>
            <trustkit-config enforcePinning="true"></trustkit-config>
        </domain-config>
    </network-security-config>

    Referencing

    The next step is to reference the network_security_config.xml in your AndroidManifest.xml.

    <application
    ....
    android:networkSecurityConfig="@xml/network_security_config"
    </application>
    

    The last step required is to initialize TrustKit with the Network Security Configuration XML file in your code. It's important that TrustKit is only initialized once.

    public class SecureApplication extends Application {
        @Override
        public void onCreate() {
            ...
            TrustKit.initializeWithNetworkSecurityConfiguration(this, R.xml.network_security_config);
        }
    ...
    }

    Usage

    Now that TrustKit has been configured and initialized, we are now able to perform SSL pinning using OkHttp.

    public Call createRequest(okhttp3.Callback callback) { 
    
    URL url = new URL("https://www.google.com"); 
    String host = url.getHost(); 
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); 
    
    SSLSocketFactory sslSocketFactory = TrustKit.getInstance().getSSLSocketFactory(host); 
    X509TrustManager trustManager = TrustKit.getInstance().getTrustManager(host); 
    connection.setSSLSocketFactory(sslSocketFactory); 
    
    OkHttpClient client = new OkHttpClient().newBuilder() 
    .sslSocketFactory(sslSocketFactory, trustManager) 
    .build(); 
    
    Request request = new Request.Builder() 
    .url(url) 
    .build(); 
    
    Call call = client.newCall(request); 
    call.enqueue(callback); 
    
    return call; 
    
    }

    Once we have created a sample network request, we can add a check for certificate errors in our OkHttp callback response.

    if (error.getCause().toString().contains("Certificate validation failed") ||
     error.getCause().toString().contains("Pin verification failed")) {
      // provide UI indication of an insecure connection
     }

    Lastly, we provide some feedback to the user if there are certificate verification errors.

    Conclusion

    As can be seen in this post, TrustKit is a very useful library to perform pinning on lower API levels whilst still keeping the same configuration interface as Android N's pinning. Using the SPKI for pinning also reduces the overheads with certificate management in mobile applications and can enhance security using the anonymized certificate information.

    For more information and examples, check out the Feedhenry Secure Android Template.


    Red Hat Mobile Application Platform is available for download, and you can read more at Red Hat Mobile Application Platform.

    Recent Posts

    • Kubernetes MCP server: AI-powered cluster management

    • Unlocking the power of OpenShift Service Mesh 3

    • Run DialoGPT-small on OpenShift AI for internal model testing

    • Skopeo: The unsung hero of Linux container-tools

    • Automate certificate management in OpenShift

    Red Hat Developers logo LinkedIn YouTube Twitter Facebook

    Platforms

    • Red Hat AI
    • Red Hat Enterprise Linux
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    Build

    • Developer Sandbox
    • Developer Tools
    • Interactive Tutorials
    • API Catalog

    Quicklinks

    • Learning Resources
    • E-books
    • Cheat Sheets
    • Blog
    • Events
    • Newsletter

    Communicate

    • About us
    • Contact sales
    • Find a partner
    • Report a website issue
    • Site Status Dashboard
    • Report a security problem

    RED HAT DEVELOPER

    Build here. Go anywhere.

    We serve the builders. The problem solvers who create careers with code.

    Join us if you’re a developer, software engineer, web designer, front-end designer, UX designer, computer scientist, architect, tester, product manager, project manager or team lead.

    Sign me up

    Red Hat legal and privacy links

    • About Red Hat
    • Jobs
    • Events
    • Locations
    • Contact Red Hat
    • Red Hat Blog
    • Inclusion at Red Hat
    • Cool Stuff Store
    • Red Hat Summit
    © 2025 Red Hat

    Red Hat legal and privacy links

    • Privacy statement
    • Terms of use
    • All policies and guidelines
    • Digital accessibility

    Report a website issue