How do you configure OkHttp's CertificatePinner on the client a Retrofit app uses, and what does a Retrofit call see when no pin matches?
answer
- a builder of host patterns
- hash of the public key
- any pin in the chain matches
- checked after the handshake
- an IOException, not HttpException
basics
~20 sBuild a CertificatePinner with add(host, "sha256/...") for a primary and a backup key, set it with certificatePinner() on the OkHttpClient given to Retrofit, and expect a mismatch to fail the call with SSLPeerUnverifiedException, an IOException, before any request is sent.
solid answer
~40 sI build `CertificatePinner.Builder().add("api.example.com", "sha256/<primary>", "sha256/<backup>").build()` and set it with `OkHttpClient.Builder().certificatePinner()` on the client passed to `Retrofit.Builder.client()`. Each pin is a base64 SHA-256 hash of a certificate's Subject Public Key Info, not of the whole certificate, so a renewed certificate on the same key still matches. After a normal, successful TLS handshake, OkHttp checks that at least one pin for the host matches some certificate in the validated chain; hosts with no pin are not checked. On a mismatch it throws `SSLPeerUnverifiedException` with "Certificate pinning failure!" and the chain's hashes. That is an `IOException`, so a suspend method throws it rather than `HttpException`, and OkHttp does not retry it. I pin only in release builds, with at least one backup pin, because debugging proxies cannot pass a pin.
code
kotlin · 22 linesimport okhttp3.CertificatePinner
import okhttp3.OkHttpClient
import retrofit2.Retrofit
fun buildRetrofit(release: Boolean): Retrofit {
val builder = OkHttpClient.Builder()
if (release) {
builder.certificatePinner(
CertificatePinner.Builder()
.add(
"api.example.com",
"sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=", // current key
"sha256/BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB=", // backup key
)
.build(),
)
}
return Retrofit.Builder()
.baseUrl("https://api.example.com/")
.client(builder.build())
.build()
}go deeper
Know that pinning is configured with CertificatePinner on the OkHttpClient Retrofit uses, and that pins are sha256 hashes listed per host.
Explain what a pin hashes, when OkHttp checks it, how host patterns match, and which exception a Retrofit call receives on a mismatch.
Show the operational side: release-only pinning, a backup pin per host, telling pin failures apart from ordinary network errors, and never retrying them.
Weigh whether the app should pin at all against the server team's freedom to change keys, and who owns the pins once builds are in users' hands.
## What CertificatePinner checks TLS already verifies that the server's certificate chains to a certificate authority the device trusts. `okhttp3.CertificatePinner` adds a narrower rule on top: for the hosts you list, the chain must also contain **one of the public keys you named**. - A **pin** is the string `sha256/` followed by the base64 SHA-256 hash of a certificate's **Subject Public Key Info**, the encoded public key. SHA-1 pins (`sha1/`) are still accepted, but SHA-256 is preferred. - Because it hashes the key, not the certificate, a certificate reissued on the same key pair still matches. - OkHttp runs the check **after a successful TLS handshake and before the connection is used**. It normally first cleans the peer chain down to the certificates that lead to a trusted root, then passes if any pin configured for the hostname matches any certificate in that chain: the leaf, an intermediate or the root. - A host that matches no configured pattern is not checked at all. ## Configuring it for Retrofit Pinning is a property of the `OkHttpClient`, so it goes on the client you pass to `Retrofit.Builder.client()`: 1. Build a `CertificatePinner` with `CertificatePinner.Builder().add(pattern, pin1, pin2)` for each host pattern. 2. Set it with `OkHttpClient.Builder().certificatePinner(pinner)`. 3. Pass that client to Retrofit. Every service built from that `Retrofit` instance is then pinned for the listed hosts. Host patterns follow a small grammar: | Pattern | Matches | Does not match | |---|---|---| | `api.example.com` | exactly that host | `example.com`, `eu.api.example.com` | | `*.example.com` | one extra label: `api.example.com` | `example.com`, `eu.api.example.com` | | `**.example.com` | any number of labels, including none | hosts outside `example.com` | Asterisks are allowed only in the leftmost label; `add()` rejects any other form with `IllegalArgumentException`. If several patterns match one host, any one of their pins is enough. ## When the check runs - It runs when a connection is **established**, not per request. Calls that reuse a pooled connection to the same host do not repeat it, so the cost is paid once per connection. - It runs for every client configured with the pinner, including clients derived from it with `newBuilder()`, which copy the pinner along with everything else. - `CertificatePinner.DEFAULT`, an empty pinner, is what a client uses when you set none: nothing is pinned. ## Getting the hashes - `CertificatePinner.pin(certificate)` returns the `sha256/...` string for a certificate you already hold. - OkHttp's documentation suggests a trick: configure a deliberately wrong pin, make one request **on a trusted network with no interception proxy running**, and copy the real hashes from the exception message, which lists every certificate in the peer chain with its pin. ## What a Retrofit call sees on a mismatch - OkHttp throws `javax.net.ssl.SSLPeerUnverifiedException` whose message starts with "Certificate pinning failure!" and lists the peer chain's pins and the pins configured for the host. - No HTTP request is sent and no HTTP response exists. A suspend method therefore throws that exception, which is an `IOException`, not `HttpException`; a `Response<T>` return type does not help; `Call.enqueue` reports it through `onFailure`. - OkHttp's recovery logic treats it as permanent and does not try another route. A retry interceptor should rethrow it too. - To the app this looks like a network failure, so it is worth logging it separately: a spike usually means a server key changed or someone is intercepting traffic. ## Release-only pins and backup pins - Interception proxies used for debugging present their own certificate, which no pin matches. Many teams set the pinner only in release builds, or only when a release flag is on, and test the release configuration before shipping. - **Always pin more than one key.** If the only pinned key is replaced, every installed build that pins it stops talking to the server until users update. Choosing which keys to pin, planning backup pins and rotating keys over years are mobile security design topics; here the point is that `add()` takes several pins per host for exactly this reason. - `CertificatePinner` cannot rescue a self-signed certificate that the platform's `TrustManager` rejects: the handshake fails first. - OkHttp's own documentation warns that pinning limits the server team's ability to change certificates, and asks you not to pin without their agreement.
- The server team renews the API certificate with the same key pair; do pinned builds keep working?Yes. A `CertificatePinner` pin hashes the certificate's Subject Public Key Info, so a new certificate issued for the same key produces the same `sha256/` value. Pinned builds break only when no pinned key appears anywhere in the validated chain, for example when the leaf key and every pinned intermediate or root key change together.
- Why pin `**.example.com` rather than `*.example.com` for an API that uses several regional hosts?With `CertificatePinner`, `*.example.com` matches exactly one extra label, so `eu.api.example.com` and the bare `example.com` would go unpinned without any error. `**.example.com` matches any number of labels, including none, which is why OkHttp's documentation calls it the best choice for most apps.
A building's security desk lets in anyone whose badge comes from an approved agency; pinning adds a short list of faces for one door. If the regular courier is replaced and no second face was on the list, nobody gets through that door until the list changes.
- A pin is the hash of the whole certificate, so every renewal breaks it.
- A pinning failure shows up as an HttpException with an error status.
- Pinning replaces normal certificate validation.
- *.example.com also protects example.com and deeper subdomains.
- One pin per host is enough.
- OkHttp retries a pin mismatch on another route before failing.