With KeyGenParameterSpec in the Android Keystore, how do you generate an AES-GCM key for a session token, and how must encryption handle the IV?
answer
- purposes, block mode, padding
- GCM pairs with NoPadding
- randomized encryption is on by default
- read cipher.iv after init
- GCMParameterSpec when decrypting
basics
~10 sBuild the spec with PURPOSE_ENCRYPT or PURPOSE_DECRYPT, BLOCK_MODE_GCM and ENCRYPTION_PADDING_NONE, generate it with KeyGenerator in AndroidKeyStore, let Cipher pick a random IV, store cipher.iv beside the ciphertext, and decrypt with GCMParameterSpec.
solid answer
~30 sI build `KeyGenParameterSpec.Builder(alias, PURPOSE_ENCRYPT or PURPOSE_DECRYPT)` with `setBlockModes(KeyProperties.BLOCK_MODE_GCM)` and `setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)`, then generate it with `KeyGenerator.getInstance(KEY_ALGORITHM_AES, "AndroidKeyStore")`. Those authorizations are fixed: a key generated for GCM rejects CBC or any other mode. To encrypt, I call `Cipher.getInstance("AES/GCM/NoPadding")` and `init(ENCRYPT_MODE, key)` **without** an IV, because randomized encryption is required by default and the Keystore rejects a caller-provided IV when encrypting. After `doFinal` I save `cipher.iv` next to the ciphertext. To decrypt, I init with `DECRYPT_MODE` and `GCMParameterSpec(128, iv)`. If the ciphertext or IV was altered, `doFinal` fails because the GCM tag does not verify.
code
kotlin · 28 linesprivate const val ALIAS = "session_token_key"
fun createTokenKey(): SecretKey {
val spec = KeyGenParameterSpec.Builder(
ALIAS,
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.setKeySize(256)
.build()
val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore")
generator.init(spec)
return generator.generateKey()
}
fun encrypt(key: SecretKey, token: ByteArray): Pair<ByteArray, ByteArray> {
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
cipher.init(Cipher.ENCRYPT_MODE, key) // no IV passed: the Keystore picks one
val ciphertext = cipher.doFinal(token)
return cipher.iv to ciphertext // store both
}
fun decrypt(key: SecretKey, iv: ByteArray, ciphertext: ByteArray): ByteArray {
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
cipher.init(Cipher.DECRYPT_MODE, key, GCMParameterSpec(128, iv))
return cipher.doFinal(ciphertext)
}go deeper
Recall the three builder calls a token key needs: the purposes, setBlockModes with GCM and setEncryptionPaddings with no padding.
Explain why encryption passes no IV, where cipher.iv comes from, and how GCMParameterSpec carries the IV back for decryption.
Catch the review bugs: a home-made IV, a lost IV, a transformation the key is not authorized for, and a tag failure handled as a crash instead of a sign-in.
Set one shared helper for Keystore encryption so every feature uses the same spec, IV storage format and failure handling.
## The spec, call by call A **`KeyGenParameterSpec`** is the recipe the Android Keystore uses to create a key and the list of **authorizations** it will enforce for that key's whole life. For a session-token key in a time-clock app, the relevant builder calls are: | Builder call | What it fixes | Why it matters here | |---|---|---| | `Builder(alias, PURPOSE_ENCRYPT or PURPOSE_DECRYPT)` | The alias and the allowed purposes | The key can encrypt and decrypt, and nothing else | | `setBlockModes(BLOCK_MODE_GCM)` | The only block mode the key accepts | Required for symmetric encryption keys | | `setEncryptionPaddings(ENCRYPTION_PADDING_NONE)` | The only padding the key accepts | GCM is used with `NoPadding` | | `setKeySize(256)` | AES key length | Otherwise an algorithm-specific default applies | The `KeyGenParameterSpec` source states that block modes **must be specified** for symmetric encryption keys, and that attempts to use the key with any other block mode or padding are rejected. The key is generated with `KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore")`, `init(spec)` and `generateKey()`, and the platform's own AES-GCM example uses the same calls, minus `setKeySize`. ## Encrypting: let the Keystore choose the IV GCM needs an **initialization vector (IV)** that is unique per encryption under one key. The Keystore makes that the default: `setRandomizedEncryptionRequired` defaults to `true`, and its documentation says that for block modes that use an IV (GCM, CBC, CTR), **caller-provided IVs are rejected when encrypting**. The documented approach is: 1. Call `Cipher.getInstance("AES/GCM/NoPadding")`. 2. Call `cipher.init(Cipher.ENCRYPT_MODE, key)` with no parameter spec, so a random IV is generated. 3. Call `doFinal(plaintext)`, then read `cipher.iv` (Kotlin's view of `getIV()`). 4. Store the IV and the ciphertext together; the IV is not secret. Turning randomized encryption off is possible, but the source lists alternatives to try first, starting with letting the `Cipher` generate the IV. ## Decrypting Decryption needs the same IV, given back through a `GCMParameterSpec` whose first argument is the authentication tag length in bits: - `cipher.init(Cipher.DECRYPT_MODE, key, GCMParameterSpec(128, iv))` - `cipher.doFinal(ciphertext)` returns the token bytes. Because GCM is an **authenticated** mode, a modified ciphertext or a wrong IV makes `doFinal` fail instead of returning garbage. Treat that as a lost session and sign the user in again. Why authenticated modes behave this way is cipher theory covered separately; here it is enough to know the failure surfaces at `doFinal`. ## Storing the result The Keystore holds only the key. The app writes the IV and ciphertext wherever it keeps small values: a preferences file or a typed store. A simple layout is the IV length, the IV, then the ciphertext, or two separate fields. ## Checking a spec in code review A reviewer reading a pull request that adds a Keystore key can check a short list: - The alias is a constant, so generation and lookup cannot drift apart. - The purposes are the minimum the feature needs; a token key needs encrypt and decrypt, not sign. - The block mode and padding pair up: `BLOCK_MODE_GCM` with `ENCRYPTION_PADDING_NONE`, and the `Cipher` transformation string names the same pair. - Encryption passes no IV, and both `cipher.iv` and the ciphertext are written to storage. - Decryption passes `GCMParameterSpec` with the stored IV, and a failing `doFinal` leads to sign-in rather than a crash. - Key work runs off the main thread, as the Keystore documentation advises. ## Failure modes reviewers catch - **Passing a home-made IV when encrypting.** With the default spec the Keystore rejects it; even if randomized encryption is switched off, a reused IV breaks GCM. - **Forgetting the IV.** Without the exact IV the ciphertext cannot be decrypted. - **Mismatched transformation.** `"AES/CBC/PKCS7Padding"` against a GCM-only key is rejected, because the authorizations were fixed at generation. - **ECB.** With randomized encryption required, transformations without that property, such as ECB, are prohibited. - **Changing the spec later.** Authorizations cannot be edited; a different configuration means a new key under a new alias and re-encrypting the data.
- Why does the Keystore reject an IV the app supplies when encrypting?Because `setRandomizedEncryptionRequired` defaults to `true`. Under that rule the Keystore only allows encryption that produces different ciphertexts for the same plaintext, so for IV-based modes like GCM it refuses caller-provided IVs and generates a random one. The app reads it with `cipher.iv` after `init`.
- Can the team later allow CBC on the same key?No. A key's authorizations, including its block modes, are fixed at generation and enforced by the Keystore. Supporting another mode means generating a new key under a new alias, decrypting the existing data with the old key, re-encrypting it with the new one and deleting the old entry.
- What happens if the stored ciphertext or IV is altered?GCM is authenticated, so `doFinal` throws instead of returning plaintext: the tag computed over the altered data does not match. The app cannot recover the token from that blob and should clear it and send the user through sign-in again.
- Always generate your own IV and pass it to Cipher.init when encrypting
- setBlockModes is optional because the mode is chosen at encryption time
- ECB is fine for a token because it fits in a single block
- The IV is secret and must be stored in the Keystore as well
- GCM needs PKCS7 padding, just like CBC