Skip to main content
Redhat Developers  Logo
  • AI

    Get started with AI

    • Red Hat AI
      Accelerate the development and deployment of enterprise AI solutions.
    • AI learning hub
      Explore learning materials and tools, organized by task.
    • AI interactive demos
      Click through scenarios with Red Hat AI, including training LLMs and more.
    • AI/ML learning paths
      Expand your OpenShift AI knowledge using these learning resources.
    • AI quickstarts
      Focused AI use cases designed for fast deployment on Red Hat AI platforms.
    • No-cost AI training
      Foundational Red Hat AI training.

    Featured resources

    • OpenShift AI learning
    • Open source AI for developers
    • AI product application development
    • Open source-powered AI/ML for hybrid cloud
    • AI and Node.js cheat sheet

    Red Hat AI Factory with NVIDIA

    • Red Hat AI Factory with NVIDIA is a co-engineered, enterprise-grade AI solution for building, deploying, and managing AI at scale across hybrid cloud environments.
    • Explore the solution
  • Learn

    Self-guided

    • Documentation
      Find answers, get step-by-step guidance, and learn how to use Red Hat products.
    • Learning paths
      Explore curated walkthroughs for common development tasks.
    • Guided learning
      Receive custom learning paths powered by our AI assistant.
    • See all learning

    Hands-on

    • Developer Sandbox
      Spin up Red Hat's products and technologies without setup or configuration.
    • Interactive labs
      Learn by doing in these hands-on, browser-based experiences.
    • Interactive demos
      Click through product features in these guided tours.

    Browse by topic

    • AI/ML
    • Automation
    • Java
    • Kubernetes
    • Linux
    • See all topics

    Training & certifications

    • Courses and exams
    • Certifications
    • Skills assessments
    • Red Hat Academy
    • Learning subscription
    • Explore training
  • Build

    Get started

    • Red Hat build of Podman Desktop
      A downloadable, local development hub to experiment with our products and builds.
    • Developer Sandbox
      Spin up Red Hat's products and technologies without setup or configuration.

    Download products

    • Access product downloads to start building and testing right away.
    • Red Hat Enterprise Linux
    • Red Hat AI
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    Featured

    • Red Hat build of OpenJDK
    • Red Hat JBoss Enterprise Application Platform
    • Red Hat OpenShift Dev Spaces
    • Red Hat Developer Toolset

    References

    • E-books
    • Documentation
    • Cheat sheets
    • Architecture center
  • Community

    Get involved

    • Events
    • Live AI events
    • Red Hat Summit
    • Red Hat Accelerators
    • Community discussions

    Follow along

    • Articles & blogs
    • Developer newsletter
    • Videos
    • Github

    Get help

    • Customer service
    • Customer support
    • Regional contacts
    • Find a partner

    Join the Red Hat Developer program

    • Download Red Hat products and project builds, access support documentation, learning content, and more.
    • Explore the benefits

Android SPKI Pinning with TrustKit

October 26, 2017
Tom Jackman
Related topics:
Security

    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

    • Trusted software factory: Building trust in the agentic AI era

    • Build a zero trust AI pipeline with OpenShift and RHEL CVMs

    • Red Hat Hardened Images: Top 5 benefits for software developers

    • How EvalHub manages two-layer Kubernetes control planes

    • Tekton joins the CNCF as an incubating project

    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
    © 2026 Red Hat

    Red Hat legal and privacy links

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

    Chat Support

    Please log in with your Red Hat account to access chat support.