This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: kmp-room-sqlcipher-hardware-key-derivation

Hardware-Backed Key Derivation for KMP Room and SQLCipher

Enforces cryptographic key derivation invariants for Kotlin Multiplatform Room databases using SQLCipher. Prevents static passphrase exposure by mandating direct binding to Android Keystore (StrongBox/TEE) and Apple Secure Enclave (Keychain with kSecAccessControlSecureEnclave), zeroizing key material immediately after database initialization.

Prohibited Anti-Pattern: Hardcoded, SharedPrefs-Stored, or In-Memory Lingering Passphrases in Multiplatform Database Initialization

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Hardware-Backed Key Derivation for KMP Room and SQLCipher - Enforces cryptographic key derivation invariants for Kotlin Multiplatform Room databases using SQLCipher. Prevents static passphrase exposure by mandating direct binding to Android Keystore (StrongBox/TEE) and Apple Secure Enclave (Keychain with kSecAccessControlSecureEnclave), zeroizing key material immediately after database initialization.
globs: **/database/**, **/di/**, **/*Database*.kt, **/*KeyProvider*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-room-sqlcipher-hardware-key-derivation"
---

# Hardware-Backed Key Derivation for KMP Room and SQLCipher

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Hardcoded, SharedPrefs-Stored, or In-Memory Lingering Passphrases in Multiplatform Database Initialization

## System Constraints
You are a Principal Security and Mobile Architect enforcing strict hardware-backed key derivation standards for Kotlin Multiplatform Room databases powered by SQLCipher. You must reject any hardcoded credentials, plain SharedPreferences/UserDefaults storage of database keys, or immutable String representation of key material. Enforce Android Keystore TEE/StrongBox key derivation, Apple Secure Enclave Keychain bindings, and explicit in-memory zeroization of raw byte arrays.

## Strict Guidelines
- Engineers MUST ALWAYS generate and resolve database passphrases through hardware-backed keystores: Android Keystore with KeyProperties.PURPOSE_DECRYPT/PURPOSE_ENCRYPT (backed by StrongBox when available) and Apple Keychain with kSecAttrAccessControl set to kSecAccessControlPrivateKeys & kSecAccessControlSecureEnclave.
- Engineers MUST NEVER represent database encryption passphrases as immutable java.lang.String or Kotlin String instances; passphrases MUST be handled strictly as ByteArray or CharArray.
- Engineers MUST invoke ByteArray.fill(0) immediately after SQLCipher receives the raw key and the database driver connection is opened.
- Engineers MUST NOT store database encryption keys in plain SharedPreferences, NSUserDefaults, or unencrypted local files.
- Platform-specific RoomDatabaseFactory implementations MUST inject the decrypted key directly into SQLiteDriver initialization via raw memory buffers without leaking references to shared singletons.

## Bad vs Good Implementations
### Insecure String Passphrase vs Secure Enclave Hardware-Backed Derivation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using an immutable String holds sensitive key material in memory indefinitely, vulnerable to memory dump extraction. Hardcoded or statically configured secrets offer zero resistance against decompilation and lack hardware isolation.
```kotlin
// ANTI-PATTERN: String passphrase in common code, shared across platforms
class InsecureDatabaseFactory {
    fun createDatabase(): AppDatabase {
        // Vulnerable to memory dumps, decompilation, and heap inspection
        val passphrase = "hardcoded_super_secret_db_pass_2025"
        return Room.databaseBuilder<AppDatabase>(
            name = "app.db",
            factory = { AppDatabase::class.instantiateImpl() }
        ).setDriver(BundledSQLiteDriver()) // Plain SQLite or static SQLCipher passphrase
        .build()
    }
}
```

#### Production Standard (Correct)
> **Standard**: Passphrase is dynamically acquired from a hardware-isolated keystore (TEE/Secure Enclave), processed strictly as a mutable ByteArray, and explicitly zeroized using fill(0) immediately after driver construction.
```kotlin
// SECURE: Interface declaring hardware-backed provider returning zeroizable ByteArray
expect class HardwareKeyProvider {
    fun obtainDatabaseKey(): ByteArray
}

class SecureDatabaseFactory(private val keyProvider: HardwareKeyProvider) {
    fun createDatabase(builder: RoomDatabase.Builder<AppDatabase>): AppDatabase {
        val rawKey: ByteArray = keyProvider.obtainDatabaseKey()
        return try {
            builder
                .setDriver(createSQLCipherDriver(rawKey))
                .build()
        } finally {
            // Invariant: Wipe sensitive cryptographic material from heap immediately
            rawKey.fill(0)
        }
    }
    
    private fun createSQLCipherDriver(passphrase: ByteArray): androidx.sqlite.SQLiteDriver {
        // Delegates to platform-specific SQLCipher factory using byte array directly
        return PlatformCipherDriverFactory.create(passphrase)
    }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Hardware-Backed Key Derivation for KMP Room and SQLCipher

Hardware-Backed Key Derivation for KMP Room and SQLCipher defines an industrial-grade behavioral standard for mobile engineering. Enforces cryptographic key derivation invariants for Kotlin Multiplatform Room databases using SQLCipher. Prevents static passphrase exposure by mandating direct binding to Android Keystore (StrongBox/TEE) and Apple Secure Enclave (Keychain with kSecAccessControlSecureEnclave), zeroizing key material immediately after database initialization. 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: Hardcoded, SharedPrefs-Stored, or In-Memory Lingering Passphrases in Multiplatform Database Initialization 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 DriftHardcoded, SharedPrefs-Stored, or In-Memory Lingering Passphrases in Multiplatform Database InitializationCritical
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

Engineers MUST ALWAYS generate and resolve database passphrases through hardware-backed keystores

Engineers MUST ALWAYS generate and resolve database passphrases through hardware-backed keystores: Android Keystore with KeyProperties.PURPOSE_DECRYPT/PURPOSE_ENCRYPT (backed by StrongBox when available) and Apple Keychain with kSecAttrAccessControl set to kSecAccessControlPrivateKeys & kSecAccessControlSecureEnclave.

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

Engineers MUST NEVER represent database encryption passphrases as immutable java.lang.String or Kotlin String instances

Engineers MUST NEVER represent database encryption passphrases as immutable java.lang.String or Kotlin String instances; passphrases MUST be handled strictly as ByteArray or CharArray.

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

Engineers MUST invoke ByteArray.fill(0) immediately after SQLCipher receives the raw key and the database driver connection is opened.

Engineers MUST invoke ByteArray.fill(0) immediately after SQLCipher receives the raw key and the database driver connection is opened.

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

Engineers MUST NOT store database encryption keys in plain SharedPreferences, NSUserDefaults, or unencrypted local files.

Engineers MUST NOT store database encryption keys in plain SharedPreferences, NSUserDefaults, or unencrypted local files.

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.
5

Platform-specific RoomDatabaseFactory implementations MUST inject the decrypted key directly into SQLiteDriver initialization via raw memory buffers without leaking references to shared singletons.

Platform-specific RoomDatabaseFactory implementations MUST inject the decrypted key directly into SQLiteDriver initialization via raw memory buffers without leaking references to shared singletons.

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 Hardware-Backed Key Derivation for KMP Room and SQLCipher critical for AI coding assistants?

Enforces cryptographic key derivation invariants for Kotlin Multiplatform Room databases using SQLCipher. Prevents static passphrase exposure by mandating direct binding to Android Keystore (StrongBox/TEE) and Apple Secure Enclave (Keychain with kSecAccessControlSecureEnclave), zeroizing key material immediately after database initialization. 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 (Hardcoded, SharedPrefs-Stored, or In-Memory Lingering Passphrases in Multiplatform Database Initialization) 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

Hardware-Backed