This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: android-security-keystore

Android Keystore & EncryptedSharedPreferences Hardening

Hardware-backed security architecture for Android. Mandates AES-256-GCM encryption for stored user tokens and private keys using Android Keystore and Jetpack Security EncryptedSharedPreferences; forbids world-readable files.

Prohibited Anti-Pattern: AI stores API tokens and sensitive user data in unencrypted plaintext SharedPreferences or world-readable files.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Android Keystore & EncryptedSharedPreferences Hardening - Hardware-backed security architecture for Android. Mandates AES-256-GCM encryption for stored user tokens and private keys using Android Keystore and Jetpack Security EncryptedSharedPreferences; forbids world-readable files.
globs: **/*Storage*.kt, **/*Keystore*.kt, **/*SecureStorage*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/android-security-keystore"
---

# Android Keystore & EncryptedSharedPreferences Hardening

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: AI stores API tokens and sensitive user data in unencrypted plaintext SharedPreferences or world-readable files.

## System Constraints
You are an Android platform security engineer. NEVER save sensitive auth tokens, passwords, or personal credentials in default unencrypted SharedPreferences. In Android apps, use Jetpack Security EncryptedSharedPreferences backed by hardware-backed MasterKeys from Android Keystore.

## Strict Guidelines
- Never use standard Context.getSharedPreferences() for authentication tokens; use EncryptedSharedPreferences.
- Generate cryptographic keys using MasterKey.Builder with MasterKey.KeyScheme.AES256_GCM backed by Android Keystore (StrongBox / TEE).
- Never export BroadcastReceivers, Services, or Activities with android:exported='true' unless explicitly intended for public system consumption.
- Store large local relational data with SQLCipher or Room database encryption.

## Bad vs Good Implementations
### Hardware-Backed EncryptedSharedPreferences vs Insecure Plaintext Storage

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Plaintext XML files in /data/data/com.app/shared_prefs are trivial to inspect via adb backup, rooted devices, or backup exploits.
```kotlin
// ANTI-PATTERN: Storing auth tokens in cleartext SharedPreferences
// Anyone with root access or ADB backup can read this file directly in plaintext!
val prefs = context.getSharedPreferences("app_prefs", Context.MODE_PRIVATE)
prefs.edit().putString("auth_token", "eyJhbGciOiJIUzI1NiIsIn...").apply()
```

#### Production Standard (Correct)
> **Standard**: Uses hardware-isolated Trusted Execution Environment (TEE) or StrongBox key store; even with root privileges, data cannot be decrypted without the hardware key.
```kotlin
// PRODUCTION STANDARD: Jetpack Security with Android Keystore Hardware Root of Trust
import androidx.security.crypto.EncryptedSharedPreferences
import androidx.security.crypto.MasterKey

fun getSecurePreferences(context: Context): SharedPreferences {
    // 1. Create or retrieve hardware-backed MasterKey in Android Keystore
    val masterKey = MasterKey.Builder(context)
        .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
        .setUserAuthenticationRequired(false)
        .build()

    // 2. Wrap preferences in AES-256-SIV (keys) and AES-256-GCM (values)
    return EncryptedSharedPreferences.create(
        context,
        "secure_vault_prefs",
        masterKey,
        EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
        EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
    )
}

// Token is encrypted with hardware key before touching physical flash storage
val securePrefs = getSecurePreferences(context)
securePrefs.edit().putString("auth_token", jwtToken).apply()
```

### Biometric Authentication Key Guard

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Software-only boolean checks can be bypassed using Frida or Xposed hooks.
```kotlin
// ANTI-PATTERN: Biometric prompt verified purely in UI without cryptographic key release
if (biometricAuthSuccess) { showSensitiveData() } // Vulnerable to hook/bypass
```

#### Production Standard (Correct)
> **Standard**: The cryptographic key itself is locked in hardware until the biometric sensor signals valid match.
```kotlin
// PRODUCTION STANDARD: CryptoObject backed by Biometric-gated Keystore Key
val cipher = getBiometricCipher() // Initialized with KeyGenParameterSpec requiring USER_AUTHENTICATION
val prompt = BiometricPrompt.CryptoObject(cipher) // Key only released upon real biometric hardware verification
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Android Keystore & EncryptedSharedPreferences Hardening

Android Keystore & EncryptedSharedPreferences Hardening defines an industrial-grade behavioral standard for mobile engineering. Hardware-backed security architecture for Android. Mandates AES-256-GCM encryption for stored user tokens and private keys using Android Keystore and Jetpack Security EncryptedSharedPreferences; forbids world-readable files. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: AI stores API tokens and sensitive user data in unencrypted plaintext SharedPreferences or world-readable files. Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftAI stores API tokens and sensitive user data in unencrypted plaintext SharedPreferences or world-readable files.Critical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Never use standard Context.getSharedPreferences() for authentication tokens

Never use standard Context.getSharedPreferences() for authentication tokens; use EncryptedSharedPreferences.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Generate cryptographic keys using MasterKey.Builder with MasterKey.KeyScheme.AES256_GCM backed by Android Keystore (StrongBox / TEE).

Generate cryptographic keys using MasterKey.Builder with MasterKey.KeyScheme.AES256_GCM backed by Android Keystore (StrongBox / TEE).

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Never export BroadcastReceivers, Services, or Activities with android

Never export BroadcastReceivers, Services, or Activities with android:exported='true' unless explicitly intended for public system consumption.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Store large local relational data with SQLCipher or Room database encryption.

Store large local relational data with SQLCipher or Room database encryption.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is Android Keystore & EncryptedSharedPreferences Hardening critical for AI coding assistants?

Hardware-backed security architecture for Android. Mandates AES-256-GCM encryption for stored user tokens and private keys using Android Keystore and Jetpack Security EncryptedSharedPreferences; forbids world-readable files. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (AI stores API tokens and sensitive user data in unencrypted plaintext SharedPreferences or world-readable files.) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

Related MOBILE Rules

View all rules →
1 Rule in Stack

Android