skip to content

In the Android Keystore, how does a time-clock app prefer a StrongBox-backed key and obtain a key attestation chain at enrollment, and what fails on phones without StrongBox?

level: seniorimportance: nice to knowfreq 30%

answer

  1. a feature flag on PackageManager
  2. ask, then fall back
  3. StrongBoxUnavailableException at generation
  4. attestation needs a key pair
  5. getCertificateChain(alias) goes to the server

basics

~20 s

Check FEATURE_STRONGBOX_KEYSTORE, call setIsStrongBoxBacked(true), and if generation throws StrongBoxUnavailableException, generate again without it. For attestation, set the server's challenge with setAttestationChallenge on an EC or RSA key pair and send KeyStore.getCertificateChain(alias); AES keys have no certificate.

solid answer

~40 s

StrongBox is an optional secure element, available from API 28. I check `PackageManager.FEATURE_STRONGBOX_KEYSTORE`, then call `KeyGenParameterSpec.Builder.setIsStrongBoxBacked(true)`. If the device has none, or its StrongBox does not support the algorithm or key size, generation throws `StrongBoxUnavailableException` and I generate the key again without the flag; the Keystore never downgrades silently. For attestation I generate an EC key pair with `setAttestationChallenge(serverNonce)` (API 24, up to 128 bytes) and send `KeyStore.getCertificateChain(alias)` to the server, which verifies it. Symmetric keys have no certificate, so setting a challenge on the AES token key makes `generateKey()` throw `InvalidAlgorithmParameterException`. On API 31 and later, `KeyInfo.getSecurityLevel()` tells me whether a key landed in `SECURITY_LEVEL_STRONGBOX` or `SECURITY_LEVEL_TRUSTED_ENVIRONMENT`.

code

kotlin · 24 lines
kotlin
// minSdk 28 assumed, so the StrongBox APIs need no version check.
fun generateEnrollmentKey(alias: String, challenge: ByteArray, strongBox: Boolean): KeyPair {
    val spec = KeyGenParameterSpec.Builder(alias, KeyProperties.PURPOSE_SIGN)
        .setAlgorithmParameterSpec(ECGenParameterSpec("secp256r1"))
        .setDigests(KeyProperties.DIGEST_SHA256)
        .setAttestationChallenge(challenge) // nonce from the server, up to 128 bytes
        .setIsStrongBoxBacked(strongBox)
        .build()
    val kpg = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_EC, "AndroidKeyStore")
    kpg.initialize(spec)
    return kpg.generateKeyPair()
}

fun enroll(context: Context, serverChallenge: ByteArray): Array<Certificate> {
    val hasStrongBox = context.packageManager
        .hasSystemFeature(PackageManager.FEATURE_STRONGBOX_KEYSTORE)
    try {
        generateEnrollmentKey(ALIAS, serverChallenge, strongBox = hasStrongBox)
    } catch (e: StrongBoxUnavailableException) {
        generateEnrollmentKey(ALIAS, serverChallenge, strongBox = false)
    }
    val keyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
    return keyStore.getCertificateChain(ALIAS) // send to the server for verification
}

go deeper

for a junior

Recall that StrongBox is an optional secure element requested with setIsStrongBoxBacked(true), and that attestation produces a certificate chain.

for a middle

Explain the FEATURE_STRONGBOX_KEYSTORE check, StrongBoxUnavailableException at generation, and why attestation needs an EC or RSA key pair.

for a senior

Build enrollment with a StrongBox fallback, an attested signing key separate from the AES token key, and KeyInfo.getSecurityLevel to confirm placement.

for a principal

Decide which keys earn StrongBox given its speed and algorithm limits, and what the product does when a device cannot attest.

## Two kinds of secure hardware Android Keystore keys can live in a **Trusted Execution Environment (TEE)**, an isolated area of the main processor, or, on devices running Android 9 (API 28) or later that include one, in **StrongBox**: an implementation in an embedded secure element or integrated secure enclave with its own CPU, secure storage, true random-number generator and tamper resistance. The Keystore documentation also lists StrongBox's limits: - A subset of algorithms: RSA 2048, AES 128 and 256, ECDSA and ECDH on P-256, HMAC-SHA256 and Triple DES. - **Slower**, more resource-constrained and fewer concurrent operations than the TEE. - The documentation's own caution: for most apps StrongBox is not necessary, so weigh it against the threat model. ## Requesting StrongBox, with a fallback 1. Check `context.packageManager.hasSystemFeature(PackageManager.FEATURE_STRONGBOX_KEYSTORE)`. 2. If present, call `setIsStrongBoxBacked(true)` on the `KeyGenParameterSpec.Builder`. 3. Generate the key. If StrongBox is unavailable, or does not support the requested algorithm or key size, the framework throws **`StrongBoxUnavailableException`**, a `ProviderException` subclass. 4. Catch it and generate again **without** `setIsStrongBoxBacked(true)`, as the documentation advises. The flag never falls back on its own; code that sets it unconditionally crashes enrollment on many phones. ## Checking where the key landed `KeyInfo` describes a stored key. Get it from `SecretKeyFactory.getInstance(key.algorithm, "AndroidKeyStore").getKeySpec(key, KeyInfo::class.java)` for a secret key, or the `KeyFactory` equivalent for a private key. | Method | Available | Meaning | |---|---|---| | `getSecurityLevel()` | API 31+ | `SECURITY_LEVEL_STRONGBOX`, `SECURITY_LEVEL_TRUSTED_ENVIRONMENT`, `SECURITY_LEVEL_SOFTWARE` and unknown values | | `isInsideSecureHardware()` | Deprecated, superseded by `getSecurityLevel()` | `true` for TEE or secure element, without saying which | ## Key attestation from the app's side **Key attestation** lets a server check claims about a key: that it was generated in secure hardware, and with which authorizations. On the device: 1. The server sends a fresh **challenge** (a nonce). 2. The app generates an **asymmetric** key pair, EC or RSA, with `setAttestationChallenge(challenge)`. The challenge may be up to 128 bytes. 3. The Keystore puts an extension describing the key's configuration, including the challenge, into the key's certificate. If the key is in secure hardware that supports attestation, the chain is signed up to a trustworthy root; otherwise it ends at an untrusted certificate. 4. The app reads `KeyStore.getCertificateChain(alias)` and sends every certificate to the server. Two API facts trip teams up: - **AES keys cannot be attested.** Symmetric keys have no public-key certificate, and the `KeyGenParameterSpec` source states that `KeyGenerator.generateKey()` throws `InvalidAlgorithmParameterException` when a challenge is set for an AES or HMAC key. The time-clock app therefore attests a separate EC signing key pair; the chain says nothing about its AES token key. - **The device is not the verifier.** The attestation documentation warns not to validate the chain on the same device, since a compromised system could make the check pass. Verification belongs on a trusted server and is covered with server-side attestation checks. ## Review findings that recur - **The flag set unconditionally.** `setIsStrongBoxBacked(true)` with no catch crashes enrollment on every phone without a secure element. - **A fixed challenge.** The challenge exists so a relying party can check that the key was created in response to a specific request; a constant baked into the app defeats that, so it should come fresh from the server. - **`getSecurityLevel()` called below API 31.** It needs a version check; older releases only offer `isInsideSecureHardware()`. - **One attestation stretched over every key.** A chain describes the key pair it certifies, not other keys the app holds. ## Putting it together for enrollment The time-clock app's enrollment generates the EC key pair with a challenge, preferring StrongBox and falling back on `StrongBoxUnavailableException`, sends the chain to the server, and generates its AES token key separately, also preferring StrongBox where present.

  • How do you confirm where a generated Keystore key actually landed?
    Read its `KeyInfo` through `SecretKeyFactory` or `KeyFactory` with the `AndroidKeyStore` provider and `getKeySpec(key, KeyInfo::class.java)`. On API 31 and later, `getSecurityLevel()` returns `SECURITY_LEVEL_STRONGBOX`, `SECURITY_LEVEL_TRUSTED_ENVIRONMENT` or `SECURITY_LEVEL_SOFTWARE`; earlier, the now-deprecated `isInsideSecureHardware()` only says whether it is in secure hardware.
  • Why not require StrongBox for every key the app creates?
    The Keystore documentation says StrongBox is slower, more resource-constrained, supports fewer concurrent operations and a subset of algorithms, and that most apps do not need it. Use it for a few high-value keys and keep the TEE for anything used often.
  • Can the app verify its own attestation chain before sending it?
    The attestation documentation warns against validating on the same device: if that device's system is compromised, the check itself can be made to pass. The app collects and forwards the chain; a trusted server verifies it.

  • setIsStrongBoxBacked(true) quietly falls back to the TEE when StrongBox is missing
  • Set an attestation challenge on the AES token key to prove it is in hardware
  • The app can check its own attestation chain on the device and trust the result
  • StrongBox is faster than the TEE because it is dedicated hardware
  • isInsideSecureHardware returning true proves the key is in StrongBox

Assumes API 28 or later for setIsStrongBoxBacked and StrongBoxUnavailableException and API 31 or later for KeyInfo.getSecurityLevel; setAttestationChallenge exists from API 24.