# Security

> Encrypted database (SQLite3MC), biometrics as an access gate, and care with local data.

Source: https://crossfly.dev/docs/best-practices/seguranca — CrossFly documentation. Full docs as one file: https://crossfly.dev/llms-full.txt

# Security

Two practical pillars for protecting data on the device: **encrypted database** and **biometrics as an
access gate**.

## Encrypted database (SQLite3MC)
Open SQLite with a key — **ChaCha20-Poly1305** cipher by default (or `SQLCIPHER`):
```java
byte[] chave = derivarChaveDaSenha(senhaUsuario);   // ⚠️ derive from password with a KDF — NEVER hardcode
try (SqliteDb db = SqliteDb.open("cofre.db", chave)) {
   // … data transparently encrypted …
   db.rekey(novaChave);                              // swaps the key (e.g. when the user changes the password)
}
```
- **Zero cost without a key, transparent cipher with a key** — without a key it's plain SQLite; with a
  key, everything is encrypted/decrypted on access, without changing your SQL.
- **Never hardcode the key.** Derive it from a user password with a KDF; store only the necessary
  material in the platform keystore.
- Be careful when **removing the cipher** (`rekey` to unprotect) — the file becomes readable in the clear.

## Biometrics as an access gate
Before a sensitive area (finance, personal data), require biometrics:
```java
if (Biometry.isAvailable()) {
   Biometry.authenticate("Acessar cofre", "Cancelar", false,
      (res, msg) -> Component.onUI(() -> {
         if (res == Biometry.AuthResult.SUCCESS) abrirCofre();
         else loginPorSenha();                 // always a fallback
      }));
} else {
   loginPorSenha();
}
```
- **Biometric data never leaves the device** — the app only receives `SUCCESS`/`FAILURE`/etc.
- Biometrics is **local** authentication: it **complements**, it does not replace, the application's
  authentication (server login).

## Other precautions
- **Clipboard:** don't copy secrets to the clipboard (`Device.clipboardCopy`) — it becomes accessible
  to other apps.
- **Files/`homeFolder`:** data in `Device.homeFolder` is not encrypted by default — use the encrypted
  database for anything sensitive.
- **Logs:** don't log passwords/tokens with `Debug.log`.

## Best practices
- Sensitive data → **encrypted SQLite**; key derived from a password (KDF), never in the code.
- Biometrics as a local gate + **always** an application-level fallback.
- No secrets in the clipboard, plaintext files, or logs.

## Common mistakes
- Hardcoded key in the code (anyone can extract it from the binary).
- Treating biometrics as if it replaced the server login.
- Storing a token/password in an unencrypted file in `homeFolder`.

## See also
- [Persistence with SQLite](/docs/data-and-services/storage-sqlite) · [Biometrics](/docs/data-and-services/device-biometry)
