# Magic Encryption documentation > Magic Encryption keeps a value opaque at rest on the device: AES-256-CBC through the Crypt facade, with the app key or a per-device key in Vault. # Installation Add `magic_encryption` to a Magic app, register its provider, create `APP_KEY` and check that `Crypt` answers. - [Install](#install) - [Requirements](#requirements) - [Create the Key](#create-the-key) - [Register the Provider](#register-the-provider) - [Verify](#verify) - [Related Documentation](#related-documentation) ## Install ```bash flutter pub add magic_encryption dart run magic:dowel plugin:install magic_encryption ``` The installer reads the package's `install.yaml` and injects `EncryptionServiceProvider` into the `providers` list of `lib/config/app.dart`. It publishes no config file: the provider reads the `app.key` that `magic:install` already wires from `APP_KEY`. ```dart import 'package:magic_encryption/magic_encryption.dart'; ``` The barrel is the only import; everything under `src/` is private. ## Requirements | Requirement | Value | |:------------|:------| | Dart | `>=3.13.0` | | Flutter | `>=3.47.0` | | Magic | `^1.0.0`, installed and bootstrapped (`lib/config/app.dart` exists) | | Dependencies | `pointycastle` for the cipher, pulled in automatically | | Device-key mode | Core's `VaultServiceProvider`, because the key lives in `Vault` | ## Create the Key ```bash dart run magic:dowel key:generate ``` The command writes `APP_KEY=base64:<32 random bytes>` to the project's `.env`, creating the file when it is missing. It replaces an `APP_KEY` line that is already there, and every value encrypted under the old key becomes unreadable. For that reason the installer does not run it: creating the key is your call. `--show` prints the line without touching `.env`. Never commit `APP_KEY`. See [App Key](https://anilcancakir.com/magic/docs/encryption/basics/app-key.md) for the accepted formats. ## Register the Provider `plugin:install` does this for you. To do it by hand, add the provider to `lib/config/app.dart`: ```dart import 'package:magic/magic.dart'; import 'package:magic_encryption/magic_encryption.dart'; final Map appConfig = { 'app': { 'key': env('APP_KEY'), 'providers': [ (app) => EncryptionServiceProvider(app), ], }, }; ``` The provider is not auto-registered. Without it nothing binds the encrypter and `Crypt.encrypt` fails. Device-key mode alone does not need it, only `VaultServiceProvider`. ## Verify ```dart import 'package:magic_encryption/magic_encryption.dart'; void main() { final String secret = Crypt.encrypt('hello'); print(secret); // base64(iv):base64(ciphertext) print(Crypt.decrypt(secret)); // hello } ``` Run it after `Magic.init` has completed. The two lines print a payload of two base64 halves joined by a colon, then `hello`. A payload differs on every run, because each call draws a fresh IV. ## Related Documentation - [Crypt](https://anilcancakir.com/magic/docs/encryption/basics/crypt.md): encrypting and decrypting, and what fails. - [App Key](https://anilcancakir.com/magic/docs/encryption/basics/app-key.md): key formats and `key:generate`. - [Device Key](https://anilcancakir.com/magic/docs/encryption/basics/device-key.md): the key kept in `Vault`. - [Wire Format](https://anilcancakir.com/magic/docs/encryption/guides/wire-format.md): the exact payload and its limits. - [Testing](https://anilcancakir.com/magic/docs/encryption/guides/testing.md): testing code that calls `Crypt`. --- # Crypt Encrypt and decrypt strings with the app key through the `Crypt` facade, and know what fails. - [Basic Usage](#basic-usage) - [Quick Reference](#quick-reference) - [Failure Modes](#failure-modes) - [What It Does Not Guarantee](#what-it-does-not-guarantee) - [Gotchas](#gotchas) - [Related Documentation](#related-documentation) ## Basic Usage ```dart import 'package:magic_encryption/magic_encryption.dart'; void main() { final String secret = Crypt.encrypt('my-secret-value'); try { final String value = Crypt.decrypt(secret); print(value); // my-secret-value } on MagicDecryptException catch (error) { print('Could not decrypt: $error'); } } ``` `Crypt` resolves the `encrypter` binding that `EncryptionServiceProvider` registers in `boot()`, so call it after `Magic.init`. Both methods are synchronous and take and return a `String`. ## Quick Reference | Member | Returns | Meaning | |:-------|:--------|:--------| | `Crypt.encrypt(value)` | `String` | `base64(iv):base64(ciphertext)`. A fresh random IV per call, so the same value never produces the same payload twice. | | `Crypt.decrypt(payload)` | `String` | The plaintext. Throws `MagicDecryptException` when the payload is malformed or does not decrypt under the key. | | `MagicDecryptException` | exception | `message` holds the reason; `toString()` prints `MagicDecryptException: `. | The key is `app.key`, normally `APP_KEY` from `.env`. To encrypt with a key that lives on the device instead, see [Device Key](https://anilcancakir.com/magic/docs/encryption/basics/device-key.md). ## Failure Modes | Situation | What happens | |:----------|:-------------| | `Crypt.encrypt('')` | Throws `RangeError`: there is no block to pad. Guard against the empty string. | | `app.key` missing or empty | `boot()` succeeds. The first `Crypt` call throws an `Exception` saying the app key is missing. | | `app.key` of the wrong size | Throws an `Exception` on the first `Crypt` call, not at boot. A raw key must be 32 bytes of UTF-8 (32 characters for ASCII); a `base64:` key must decode to 32 bytes. | | A `base64:` key that is not valid base64 | Throws an `Exception` on the first `Crypt` call. | | A payload without exactly one `:` | `decrypt` throws `MagicDecryptException` (`Invalid payload format`). | | A payload with a bad IV, partial block or broken padding | `decrypt` throws `MagicDecryptException` (`Decryption failed: ...`). | | A payload from another key | Almost always `MagicDecryptException`. Roughly one in 256 happens to unpad cleanly and returns garbage text instead of throwing. | | Decrypted bytes that are not valid UTF-8 | Decode to U+FFFD replacement characters rather than throwing. | ## What It Does Not Guarantee The payload has no MAC. A value that decrypts is not thereby proven untampered: CBC is malleable, so someone who can edit a stored payload can flip bits of the first plaintext block and decryption still succeeds. A decryption failure shown to whoever supplied the payload is a padding oracle. Use `Crypt` to keep a value opaque at rest on the device. Verify anything whose integrity matters (a token, an amount, an identity) on the server that issued it. See [Wire Format](https://anilcancakir.com/magic/docs/encryption/guides/wire-format.md) for the exact format. The app key is not a secret from someone who holds your app. `APP_KEY` is loaded from the `.env` asset, so it ships inside every build, and anyone who unpacks the build can read it. Config-key mode hides a value from people without the binary. Never put a key that a server also trusts in `APP_KEY`; for a secret kept on one device, prefer [Device Key](https://anilcancakir.com/magic/docs/encryption/basics/device-key.md). ## Gotchas | Mistake | Fix | |:--------|:----| | Calling `Crypt` before `EncryptionServiceProvider` is registered | Add it to `providers` in `lib/config/app.dart`; it is not auto-registered. | | Calling `Crypt` before `Magic.init` completes | `await Magic.init(...)` first. | | Encrypting an empty string | Check for `''` first; it throws `RangeError`. | | Treating a successful decrypt as proof of integrity | There is no MAC. Verify integrity on the server. | | Showing `MagicDecryptException` to the party that sent the payload | Log it, answer with one generic error. | | Expecting Laravel to read the payload | The format is not Laravel's; see [Wire Format](https://anilcancakir.com/magic/docs/encryption/guides/wire-format.md). | | Sharing `APP_KEY` with a server so it can read or write payloads | The key ships inside the build, so it is not secret from anyone with the app. Exchange data through the transport. | | Encrypting a `Map` or a `List` | `Crypt` takes a `String`; encode with `jsonEncode` first and decode after `decrypt`. | ## Related Documentation - [App Key](https://anilcancakir.com/magic/docs/encryption/basics/app-key.md): the formats `app.key` accepts and `key:generate`. - [Device Key](https://anilcancakir.com/magic/docs/encryption/basics/device-key.md): encrypting with a key kept in `Vault`. - [Wire Format](https://anilcancakir.com/magic/docs/encryption/guides/wire-format.md): the payload byte by byte. - [Testing](https://anilcancakir.com/magic/docs/encryption/guides/testing.md): testing code that calls `Crypt`. --- # App Key The `app.key` that `Crypt.encrypt` and `Crypt.decrypt` use, the two formats it accepts, how `key:generate` writes it and what changing it costs. - [Basic Usage](#basic-usage) - [Quick Reference](#quick-reference) - [key:generate](#key-generate) - [Changing the Key](#changing-the-key) - [Gotchas](#gotchas) - [Related Documentation](#related-documentation) ## Basic Usage ```bash dart run magic:dowel key:generate ``` ```env APP_KEY=base64:your-generated-key-here ``` `lib/config/app.dart` reads it as `'key': env('APP_KEY')`, and `EncryptionServiceProvider` builds the encrypter from `app.key` the first time `Crypt` is used. ## Quick Reference | Format | Example shape | Rule | |:-------|:--------------|:-----| | `base64:` prefix | `base64:` plus the base64 of 32 bytes | Must decode to exactly 32 bytes. This is what `key:generate` writes. | | Raw string | 32 bytes of UTF-8 | The UTF-8 bytes of the string are the AES key. ASCII characters take one byte each, so 32 ASCII characters are 32 bytes. | Anything else fails with an `Exception` the first time `Crypt` is used, not at boot. ## key:generate | Option | Effect | |:-------|:-------| | none | Generates 32 random bytes, base64-encodes them and writes `APP_KEY=base64:...` to the project's `.env`. Replaces an existing `APP_KEY` line, adds one when absent, and creates `.env` when the file is missing. Prints a success line only, never the key, so it stays out of CI logs. | | `--show` | Prints `APP_KEY=base64:...` and leaves `.env` alone. | The command lives in `package:magic_encryption/cli.dart` and runs as a plain Dart process, with no Flutter engine behind it. ## Changing the Key The payload carries no key id, so there is no rotation. A new `APP_KEY` cannot open anything written under the old one: every stored `Crypt` value becomes unreadable (nearly always a `MagicDecryptException`). To migrate, decrypt with an encrypter built from the old key and encrypt again with the new one: ```dart import 'package:magic_encryption/magic_encryption.dart'; String reencrypt(String payload, String oldAppKey) { final MagicEncrypter oldEncrypter = MagicEncrypter.fromAppKey(oldAppKey); return Crypt.encrypt(oldEncrypter.decrypt(payload)); } ``` Run the migration while the app still has the old key available, then retire it. ## Gotchas | Mistake | Fix | |:--------|:----| | Running `key:generate` on an app that has stored ciphertext | It overwrites `APP_KEY` and orphans every value under the old key. Use `--show` to look, or migrate as above. | | Committing `.env` or `APP_KEY` | Keep the key out of version control. | | A raw key of 31 or 33 bytes | The key must be exactly 32 bytes of UTF-8, which is 32 characters when they are all ASCII. | | A `base64:` key of 16 or 24 bytes | It must decode to 32 bytes; shorter AES keys are refused. | | Non-ASCII characters in a raw key | One character can be several UTF-8 bytes, so 32 characters can be more than 32 bytes and the constructor refuses them. Use `key:generate`. | | Expecting boot to catch a bad key | The encrypter is lazy: the error appears on the first `Crypt` call. | ## Related Documentation - [Crypt](https://anilcancakir.com/magic/docs/encryption/basics/crypt.md): using the key to encrypt and decrypt. - [Device Key](https://anilcancakir.com/magic/docs/encryption/basics/device-key.md): a key that is generated on the device instead. - [Installation](https://anilcancakir.com/magic/docs/encryption/getting-started/installation.md): creating the key for the first time. --- # Device Key Encrypt with a key generated on the device and kept in `Vault`, so a value stored locally cannot be opened anywhere else. - [Basic Usage](#basic-usage) - [Quick Reference](#quick-reference) - [How the Key Is Made](#how-the-key-is-made) - [Lifecycle](#lifecycle) - [Gotchas](#gotchas) - [Related Documentation](#related-documentation) ## Basic Usage ```dart import 'package:magic_encryption/magic_encryption.dart'; Future main() async { final String secret = await Crypt.encryptWithDeviceKey('my-user-token'); final String value = await Crypt.decryptWithDeviceKey(secret); print(value); // my-user-token } ``` Register core's `VaultServiceProvider` in `providers`. Device-key mode reads and writes the key through the `Vault` facade and needs no `app.key`, so it works without `EncryptionServiceProvider` and without `APP_KEY`. ## Quick Reference | Member | Returns | Meaning | |:-------|:--------|:--------| | `Crypt.encryptWithDeviceKey(value)` | `Future` | Encrypts under the device key, creating it on first use. | | `Crypt.decryptWithDeviceKey(payload)` | `Future` | Decrypts under the device key. Throws `MagicDecryptException` like `Crypt.decrypt`. | | `Crypt.hasDeviceKey()` | `Future` | Whether `Vault` holds a device key. Never creates one. | | `Crypt.generateDeviceKey()` | `Future` | Replaces the key. Everything encrypted under the old one is lost. | | `Crypt.clearDeviceKey()` | `Future` | Deletes the key from `Vault`. Everything encrypted under it is lost. | The payload is the same `base64(iv):base64(ciphertext)` as [Crypt](https://anilcancakir.com/magic/docs/encryption/basics/crypt.md), and the same limits apply: no MAC, and `encryptWithDeviceKey('')` throws `RangeError`. ## How the Key Is Made On first use the key is read from `Vault` under the name `magic:device_encryption_key`. When it is absent, 32 characters are drawn from `A-Z`, `a-z` and `0-9` with a secure random source and stored there. The encrypter built from it is then cached in memory for the life of the process. How safe the key is depends on `Vault`'s store on that platform: the Keychain on iOS and macOS, the Keystore on Android, and a weaker store on web. ## Lifecycle - The key lives as long as the secure storage entry does. On Android, clearing app data or uninstalling the app removes it. On iOS the Keychain item can survive a reinstall, because neither `Vault` nor this package wipes it on first run. Once the key is gone and the app has restarted (a running process keeps the key in memory and does not read `Vault` again), the ciphertext it protected cannot be opened. - `generateDeviceKey()` and `clearDeviceKey()` both update the in-memory cache as well as `Vault`, so the next call uses the new state at once. - The key never leaves the device, so a server or another device cannot decrypt a payload encrypted here; on the same iOS device a reinstall can, when the Keychain item survived and you kept the ciphertext. Send data to a server through the transport, not through this cipher; see [Wire Format](https://anilcancakir.com/magic/docs/encryption/guides/wire-format.md). ## Gotchas | Mistake | Fix | |:--------|:----| | Forgetting `VaultServiceProvider` | Register core's provider; the key is stored through `Vault`. | | Calling `generateDeviceKey()` to "refresh" the key | It orphans every existing value. Call it only when the data is disposable. | | Decrypting a `Crypt.encrypt` payload with the device key, or the other way round | The two modes use different keys; keep each value with the mode that wrote it. | | Treating the device key as backed up | It is lost with the secure storage. Keep nothing here that you cannot recreate. | | Reaching for device-key mode to share data with a server | The server cannot read it. Send the data over the transport instead; a key shared with a server would ship inside the app (see [Crypt](https://anilcancakir.com/magic/docs/encryption/basics/crypt.md)). | | Changing the macOS keychain an app uses (signing with a provisioning profile after ad-hoc builds, or `macOsUsesDataProtectionKeychain` on `MagicVaultService`) | The two macOS keychains share no items and a miss looks like "never stored", so the next call generates a new device key and everything encrypted under the old one is unreadable. Pin the keychain on an app that already holds a key. | | Leaking the cached key between tests | Call `Crypt.clearDeviceKey()` in `tearDown`; see [Testing](https://anilcancakir.com/magic/docs/encryption/guides/testing.md). | ## Related Documentation - [Crypt](https://anilcancakir.com/magic/docs/encryption/basics/crypt.md): encrypting with the app key. - [App Key](https://anilcancakir.com/magic/docs/encryption/basics/app-key.md): where `APP_KEY` comes from. - [Testing](https://anilcancakir.com/magic/docs/encryption/guides/testing.md): a fake vault and the cached encrypter. --- # Wire Format The exact bytes `Crypt` and `MagicEncrypter` write, what they do not guarantee and how they differ from Laravel's `Crypt`. - [Quick Reference](#quick-reference) - [Reading a Payload](#reading-a-payload) - [Not Authenticated](#not-authenticated) - [Not Laravel](#not-laravel) - [Gotchas](#gotchas) - [Related Documentation](#related-documentation) ## Quick Reference | Part | Value | |:-----|:------| | Cipher | AES-256 in CBC mode with PKCS7 padding | | Key | 32 bytes: the UTF-8 bytes of a raw string (32 characters for ASCII), or the decoded bytes of a `base64:` key | | IV | 16 random bytes per call from a secure random source | | Plaintext | The string, UTF-8 encoded | | Payload | `base64(iv):base64(ciphertext)`, standard base64 with padding, one colon | The format is fixed. It is the one Magic 0.0.41 and earlier wrote, so changing any part orphans every stored value. ## Reading a Payload `MagicEncrypter` is the cipher behind both modes. Build one directly when you hold a key that is not `app.key`: ```dart import 'package:magic_encryption/magic_encryption.dart'; void main() { final MagicEncrypter encrypter = MagicEncrypter('0123456789abcdef0123456789abcdef'); final String payload = encrypter.encrypt('hello'); final List parts = payload.split(':'); print(parts.length); // 2: the base64 IV, then the base64 ciphertext print(encrypter.decrypt(payload)); // hello } ``` `MagicEncrypter(String key)` throws an `Exception` unless the key is 32 bytes of UTF-8 (32 characters for ASCII). `MagicEncrypter.fromAppKey(String)` also accepts a `base64:` key and throws unless it decodes to 32 bytes. `decrypt` splits on `:`, base64-decodes both halves, decrypts and decodes UTF-8 with malformed bytes replaced by U+FFFD. ## Not Authenticated There is no MAC and no AEAD tag. Two consequences follow: - CBC is malleable. Someone who can modify a stored payload can flip bits in the IV and flip the same bits in the first plaintext block, predictably. Decryption still succeeds and returns a value the attacker partly chose. - A decryption failure is observable. A caller that reports it back to whoever supplied the payload builds a padding oracle. So `Crypt` keeps a value opaque at rest on the device and is not evidence that the value is unmodified. Verify anything whose integrity matters on the server that issued it, which can hold a secret this layer cannot. ## Not Laravel Laravel's `Crypt` writes base64 of a JSON object holding the IV, the value and an HMAC, and refuses a payload whose MAC does not verify. This package writes `base64(iv):base64(ciphertext)` with no MAC. The two cannot read each other's output, so do not send a Magic payload to a Laravel `Crypt::decrypt` or the other way round. Exchange data with a server through the transport, not through this cipher. ## Gotchas | Mistake | Fix | |:--------|:----| | Passing a `Crypt` payload to Laravel's decrypter | It will not parse; the formats differ. | | Relying on a failed decrypt to catch tampering | Most tampering still decrypts. Verify integrity on the server. | | Pinning the IV in production | `MagicEncrypter.encrypt` has an `iv:` parameter for tests only; a reused IV leaks equality of plaintext prefixes. | | Building a `MagicEncrypter` from a key that is not 32 bytes of UTF-8 (32 characters for ASCII) | It throws; use `MagicEncrypter.fromAppKey` for a `base64:` key. | ## Related Documentation - [Crypt](https://anilcancakir.com/magic/docs/encryption/basics/crypt.md): the facade and its failure modes. - [App Key](https://anilcancakir.com/magic/docs/encryption/basics/app-key.md): producing and formatting the key. - [Testing](https://anilcancakir.com/magic/docs/encryption/guides/testing.md): pinning an IV to assert an exact payload. --- # Testing Test code that calls `Crypt` without a device, a keychain or a mocking library. - [Config-Key Mode](#config-key-mode) - [Device-Key Mode](#device-key-mode) - [Pinning the IV](#pinning-the-iv) - [Related Documentation](#related-documentation) ## Config-Key Mode Bind an encrypter under the `encrypter` key, the one `EncryptionServiceProvider` binds in production, and `Crypt` uses it. Every `setUp()` resets the container, as every Magic test does. ```dart import 'package:flutter_test/flutter_test.dart'; import 'package:magic/magic.dart'; import 'package:magic_encryption/magic_encryption.dart'; void main() { setUp(() { MagicApp.reset(); Magic.flush(); Magic.singleton( 'encrypter', () => MagicEncrypter('0123456789abcdef0123456789abcdef'), ); }); test('a value survives a round trip', () { expect(Crypt.decrypt(Crypt.encrypt('hello')), 'hello'); }); test('a malformed payload is refused', () { expect( () => Crypt.decrypt('not-a-payload'), throwsA(isA()), ); }); } ``` To test the provider itself, boot Magic with `'app': {'key': '...', 'providers': [(app) => EncryptionServiceProvider(app)]}`; `Magic.init` reads path_provider, so mock its channel in `setUpAll`. Do not assert that a payload from another key throws. About one wrong-key payload in 256 unpads cleanly and returns garbage, so assert instead that it never yields the plaintext. ## Device-Key Mode Swap the vault for core's fake with `Vault.fake()`. `Crypt` caches the device encrypter in a static field that `Magic.flush()` does not reset, so a key from an earlier test would outlive its fake vault: clear it in `tearDown`. ```dart import 'package:flutter_test/flutter_test.dart'; import 'package:magic/magic.dart'; import 'package:magic_encryption/magic_encryption.dart'; void main() { setUp(() { MagicApp.reset(); Magic.flush(); Vault.fake(); }); tearDown(() async { await Crypt.clearDeviceKey(); }); test('the device key is created on first use', () async { expect(await Crypt.hasDeviceKey(), isFalse); final String secret = await Crypt.encryptWithDeviceKey('token'); expect(await Crypt.hasDeviceKey(), isTrue); expect(await Crypt.decryptWithDeviceKey(secret), 'token'); }); } ``` ## Pinning the IV `MagicEncrypter.encrypt` takes an `iv:` of 16 bytes so a test can assert an exact payload. Leave it unset in production: a reused IV leaks equality of plaintext prefixes. ```dart import 'dart:convert'; import 'dart:typed_data'; import 'package:flutter_test/flutter_test.dart'; import 'package:magic_encryption/magic_encryption.dart'; void main() { test('the same key, value and IV give the same payload', () { final MagicEncrypter encrypter = MagicEncrypter('0123456789abcdef0123456789abcdef'); final Uint8List iv = Uint8List(16); final String payload = encrypter.encrypt('hello', iv: iv); expect(payload.split(':').first, base64.encode(iv)); expect(encrypter.encrypt('hello', iv: iv), payload); }); } ``` ## Related Documentation - [Crypt](https://anilcancakir.com/magic/docs/encryption/basics/crypt.md): the facade under test. - [Device Key](https://anilcancakir.com/magic/docs/encryption/basics/device-key.md): the cached encrypter and the vault. - [Wire Format](https://anilcancakir.com/magic/docs/encryption/guides/wire-format.md): what a payload contains.