> ## Documentation Index
> Fetch the complete documentation index at: https://second.tech/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Store the mnemonic securely

> Store the mnemonic in each SDK platform's secure storage, protect the mnemonic file on Barkd and the Bark CLI, and reopen the wallet from it.

Bark never stores the mnemonic for an SDK app. Your wallet app stores it and passes it to `Wallet.open()` every time it opens the wallet, at launch or on a background wake.

Barkd and the Bark CLI store the mnemonic as a file in their data directory.

## Store the mnemonic in secure storage on the Bark SDK

### Cross-platform recommendations

* **One entry in secure storage:** Store the mnemonic as a single entry in the platform's secure storage, which encrypts it with a key the operating system holds. The browser has no such storage, so for web deployments, encrypt the mnemonic yourself, preferably with a key derived from a user password.
* **Bound to the device:** Choose the settings that leave the entry out of cloud sync and out of backups restored on another device.
* **Readable without a prompt:** If your wallet app refreshes in the background, choose the setting that lets a background task read the entry once the user has unlocked the device after a restart, with no biometric prompt or password on each read ([background refresh](https://second.tech/docs/patterns/background-refresh.md#store-the-mnemonic-so-background-tasks-can-read-it)).
* **Record the mnemonic externally:** Your app should ensure that the user [records the mnemonic](https://second.tech/docs/patterns/backups.md#mnemonic-backups) outside the app, for example by writing it down, because it will be required in the event of an app failure or a lost device.
* **No logs or telemetry:** Never log the mnemonic or send it in crash reports or analytics.

### Platform-specific recommendations

> [tab] Rust
>
> Use the `keyring` crate, version 4.1 or later, with its default features. It stores the entry in Keychain Services on macOS, Credential Manager on Windows, and the Secret Service on Linux.
>
> ```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
> let entry = keyring::Entry::new("com.example.wallet", "bark-mnemonic")?;
> entry.set_password(&mnemonic.to_string())?;
> ```
>
> * **Version 3:** Enable the feature for each platform you build for. Without one, the crate falls back to a mock store that persists nothing.
> * **Windows:** To restrict the entry to one computer, create it through `keyring-core` and `windows-native-keyring-store` with the `persistence` modifier set to `Local`. By default, `keyring` writes Enterprise entries, which follow a roaming profile to other computers.
> * **Linux:** The crate needs a Secret Service provider, such as GNOME Keyring or KWallet, running in the user's session. On a machine without one, write the mnemonic to an unencrypted file readable only by the user account that runs your app, as [Barkd does](https://second.tech/docs/patterns/mnemonic-storage.md#protect-the-mnemonic-file-on-barkd-and-the-bark-cli).

> [tab] Web
>
> A web page has no secure store like the Keychain or the Android Keystore. Any script on your origin can read `localStorage` and IndexedDB. Encrypt the mnemonic before you store it. A key derived from a user password is the recommended setup:
>
> 1. Ask the user for a password when they create or import the wallet.
> 2. Derive an AES-GCM key from the password with PBKDF2-SHA256, a random 16-byte salt, and 600,000 iterations.
> 3. Encrypt the mnemonic with that key and a random 12-byte IV.
> 4. Store the salt, the IV, and the ciphertext in IndexedDB or `localStorage`. Never store the password or the key.
> 5. On every visit, ask for the password.
> 6. Derive the key again with the stored salt and decrypt the mnemonic.
> 7. Open the wallet with `createIfNotExists: false`.
>
> ```ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
> const PBKDF2_ITERATIONS = 600_000;
>
> async function deriveKey(password: string, salt: BufferSource): Promise<CryptoKey> {
>   const material = await crypto.subtle.importKey(
>     "raw", new TextEncoder().encode(password), "PBKDF2", false, ["deriveKey"],
>   );
>   return crypto.subtle.deriveKey(
>     { name: "PBKDF2", hash: "SHA-256", salt, iterations: PBKDF2_ITERATIONS },
>     material,
>     { name: "AES-GCM", length: 256 },
>     false, // the key never leaves Web Crypto
>     ["encrypt", "decrypt"],
>   );
> }
>
> export async function encryptMnemonic(mnemonic: string, password: string) {
>   const salt = crypto.getRandomValues(new Uint8Array(16));
>   const iv = crypto.getRandomValues(new Uint8Array(12));
>   const key = await deriveKey(password, salt);
>   const ciphertext = await crypto.subtle.encrypt(
>     { name: "AES-GCM", iv }, key, new TextEncoder().encode(mnemonic),
>   );
>   return { salt, iv, ciphertext }; // store in IndexedDB, or base64-encode each field for localStorage
> }
>
> export async function decryptMnemonic(
>   record: { salt: BufferSource; iv: BufferSource; ciphertext: BufferSource },
>   password: string,
> ): Promise<string> {
>   const key = await deriveKey(password, record.salt);
>   // Throws on a wrong password: AES-GCM authenticates the ciphertext.
>   const plaintext = await crypto.subtle.decrypt({ name: "AES-GCM", iv: record.iv }, key, record.ciphertext);
>   return new TextDecoder().decode(plaintext);
> }
> ```
>
> The password protects the mnemonic at rest. A script injected into your page can still read the password as the user types it, or the mnemonic once your app decrypts it.
>
> Without a password, encrypt the mnemonic under a non-extractable AES-GCM key stored in IndexedDB, with the ciphertext in `localStorage`, as Bark Wallet does by default. The wallet then unlocks on reload without a prompt. A copy of `localStorage` alone can't reveal the mnemonic. A script running on the page or a copy of the whole browser profile can.

> [tab] React Native
>
> Use `expo-secure-store` in an Expo app, or `react-native-keychain` in a bare React Native app. Pass the iOS accessibility class that background tasks need:
>
> ```ts Expo theme={"theme":{"light":"github-light","dark":"github-dark"}}
> import * as SecureStore from 'expo-secure-store';
>
> await SecureStore.setItemAsync('bark-mnemonic', mnemonic, {
>   keychainAccessible: SecureStore.AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY,
> });
> ```
>
> ```ts Bare React Native theme={"theme":{"light":"github-light","dark":"github-dark"}}
> import * as Keychain from 'react-native-keychain';
>
> await Keychain.setGenericPassword('bark-mnemonic', mnemonic, {
>   service: 'com.example.wallet.mnemonic',
>   accessible: Keychain.ACCESSIBLE.AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY,
> });
> ```
>
> * **No authentication binding:** If your wallet app refreshes in the background, don't bind the entry to authentication. In Expo, leave `requireAuthentication` off. In bare React Native, leave `accessControl` off and don't set `storage` to `AES_GCM` or `RSA`. Each of these options binds the entry to authentication.
> * **No `cloudSync` option:** Leave `cloudSync` out of every `react-native-keychain` call. Version 10 treats `cloudSync: false` as `true` and syncs the entry to iCloud Keychain.
> * **Expo on iOS:** On versions before 58, delete an existing item before you write it again with a new `keychainAccessible` value.
> * **Expo backups:** With Continuous Native Generation, the `expo-secure-store` config plugin excludes the store from Android backups. Its rules also stop backing up anything outside shared preferences. If your app already has backup rules, the plugin only logs a warning. In that case, exclude the `SecureStore` shared preferences file yourself.
> * **Bare React Native backups:** The library ships no backup rules. Exclude its DataStore file, `datastore/RN_KEYCHAIN.preferences_pb` in the `file` domain, from Auto Backup.

> [tab] Flutter
>
> Use the `flutter_secure_storage` plugin, version 11, with these options:
>
> ```dart theme={"theme":{"light":"github-light","dark":"github-dark"}}
> const storage = FlutterSecureStorage(
>   iOptions: IOSOptions(accessibility: KeychainAccessibility.first_unlock_this_device),
>   mOptions: MacOsOptions(accessibility: KeychainAccessibility.first_unlock_this_device),
>   aOptions: AndroidOptions(resetOnError: false),
> );
>
> await storage.write(key: 'bark-mnemonic', value: mnemonic);
> ```
>
> * **iOS and macOS:** The default accessibility, `unlocked`, blocks reads while the screen is locked. Set `MacOsOptions` as well, since the plugin ignores `IOSOptions` on macOS.
> * **Android:** With the default `resetOnError: true`, the plugin permanently erases its stored data when an error occurs. If your wallet app refreshes in the background, don't use `AndroidOptions.biometric()`.
> * **Android backups:** Exclude the plugin's data and key files, `FlutterSecureStorage.xml` and `FlutterSecureKeyStorage.xml` in the `sharedpref` domain, from Auto Backup.
> * **macOS entitlements:** Add the Keychain Sharing capability to both `DebugProfile.entitlements` and `Release.entitlements`.

> [tab] Swift
>
> Add the mnemonic to Keychain Services as a generic password item:
>
> ```swift theme={"theme":{"light":"github-light","dark":"github-dark"}}
> let query: [String: Any] = [
>     kSecClass as String: kSecClassGenericPassword,
>     kSecAttrService as String: "com.example.wallet",
>     kSecAttrAccount as String: "bark-mnemonic",
>     kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly,
>     kSecUseDataProtectionKeychain as String: true,
>     kSecValueData as String: Data(mnemonic.utf8),
> ]
> SecItemAdd(query as CFDictionary, nil)
> ```
>
> * **Accessibility:** Set `kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly` when you add the item. A backup restored on another device does not include the item.
> * **No biometrics on the item:** If your wallet app refreshes in the background, leave `kSecAttrAccessControl` off. A biometry-bound item needs Face ID or Touch ID before a read. A background task can't rely on reading it. With `biometryCurrentSet`, the system also invalidates the item when the user changes their enrolled fingerprints or face.
> * **macOS:** Include `kSecUseDataProtectionKeychain` in every query. macOS applies the accessibility setting only in the data protection keychain, which needs an app signed with a provisioning profile.

> [tab] Kotlin
>
> On Android, encrypt the mnemonic with an AES-256 key from the Android Keystore. On the JVM, encrypt it with a key derived from a user password, since the JDK has no OS-backed store for a secret like a mnemonic.
>
> ```kotlin Android theme={"theme":{"light":"github-light","dark":"github-dark"}}
> val keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore")
> keyGenerator.init(
>     KeyGenParameterSpec.Builder(
>         "bark-mnemonic-key",
>         KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT,
>     )
>         .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
>         .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
>         .setKeySize(256)
>         .build(),
> )
> val cipher = Cipher.getInstance("AES/GCM/NoPadding")
> cipher.init(Cipher.ENCRYPT_MODE, keyGenerator.generateKey())
> val ciphertext = cipher.doFinal(mnemonic.toByteArray())
> // Store cipher.iv and ciphertext in your app's internal storage
> ```
>
> ```kotlin JVM theme={"theme":{"light":"github-light","dark":"github-dark"}}
> val random = SecureRandom()
> val salt = ByteArray(16).also { random.nextBytes(it) }
> val iv = ByteArray(12).also { random.nextBytes(it) }
> val keyBytes = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256")
>     .generateSecret(PBEKeySpec(password, salt, 600_000, 256))
>     .encoded
> val cipher = Cipher.getInstance("AES/GCM/NoPadding")
> cipher.init(Cipher.ENCRYPT_MODE, SecretKeySpec(keyBytes, "AES"), GCMParameterSpec(128, iv))
> val ciphertext = cipher.doFinal(mnemonic.toByteArray())
> // Store salt, iv, and ciphertext. Never store the password or the key.
> ```
>
> * **Android key, once:** Generate the key in your create flow only. A second `generateKey()` under the same alias replaces the key. Your app can then no longer decrypt the stored mnemonic.
> * **Android key settings:** If your wallet app refreshes in the background, don't call `setUserAuthenticationRequired(true)` or `setUnlockedDeviceRequired(true)` on the key. The first requires user authentication for every use of the key by default. The second blocks decryption while the device is locked. Either one can stop a background job from decrypting. Android also invalidates an authentication-bound key for good when the user removes the secure lock screen.
> * **Android backups:** Exclude the file that holds the ciphertext from Auto Backup and device-to-device transfer, with `dataExtractionRules` on Android 12 and higher and `fullBackupContent` on Android 11 and lower. Your app can't decrypt a restored copy without the Keystore key, which stays on the original device.
> * **Skip `EncryptedSharedPreferences`:** Google deprecated the `androidx.security:security-crypto` library in its final release, 1.1.0.
> * **JVM:** Ask for the password on every launch. Store only the salt, the IV, and the ciphertext.

> [tab] Go
>
> Use `github.com/zalando/go-keyring`. It stores the entry in Keychain Services on macOS, Credential Manager on Windows, and the Secret Service on Linux.
>
> ```go theme={"theme":{"light":"github-light","dark":"github-dark"}}
> if err := keyring.Set("com.example.wallet", "bark-mnemonic", mnemonic); err != nil {
>     return err
> }
> ```
>
> On Linux, the library needs a Secret Service provider, such as GNOME Keyring or KWallet, running in the user's session. On a machine without one, write the mnemonic to an unencrypted file readable only by the user account that runs your app, as [Barkd does](https://second.tech/docs/patterns/mnemonic-storage.md#protect-the-mnemonic-file-on-barkd-and-the-bark-cli).

## Protect the mnemonic file on Barkd and the Bark CLI

The `mnemonic` file sits unencrypted next to the wallet database, and file permissions are its only protection.

> [tab] Barkd
>
> The [data directory](https://second.tech/docs/barkd/start.md) defaults to `~/.bark` and holds one wallet, so give each network its own, such as `~/.bark-mainnet`. Set it with `--datadir` or `BARKD_DATADIR`.
>
> * **One user, one directory:** Run `barkd` as a dedicated system user and make the data directory readable by that user only. With Docker, mount the data directory from a volume that only the `barkd` container uses.
> * **Backups copy the file:** Anything that backs up the data directory copies the mnemonic in plain text. Encrypt those backups or exclude the file from them, and back up the wallet database separately ([continuous backups](https://second.tech/docs/patterns/backups.md#continuous-backups)).
> * **Record it once, offline:** When you create the wallet, read the mnemonic once and record it offline. Do not store it in the repository, in CI variables, or in a password manager that syncs it in plain text.
> * **Leave the endpoint off:** Start `barkd` without `--expose-mnemonic` unless your product reveals the mnemonic. If you enable it, the [bearer token](https://second.tech/docs/barkd/authenticate.md) is the endpoint's only protection, so never expose `barkd` to the public internet.

> [tab] Bark CLI
>
> `bark help` prints the default data directory. A data directory holds one wallet, so give each network its own, such as `~/.bark-mainnet`. Set it with `BARK_DATADIR` ([configuration](https://second.tech/docs/getting-started/bark-cli/configuration.md)).
>
> * **One user, one directory:** Run `bark` as the user who owns the wallet and make the data directory readable by that user only.
> * **Backups copy the file:** Anything that backs up the data directory copies the mnemonic in plain text. Encrypt those backups or exclude the file from them, and back up the wallet database separately ([continuous backups](https://second.tech/docs/patterns/backups.md#continuous-backups)).
> * **Record it once, offline:** When you create the wallet, read the mnemonic once and record it offline. Do not store it in a password manager that syncs it in plain text.

> [!NOTE]
>
> Restoring a wallet balance with the mnemonic alone requires the Ark server's cooperation and does not include payment history. It resumes an in-progress exit only once the VTXO's own transaction is on-chain or in the mempool. For a full, trustless restore, make sure your app also [makes continuous backups](https://second.tech/docs/patterns/backups.md#continuous-backups) of the wallet database.

## Reopen the wallet from the stored mnemonic

Each time your wallet app starts or wakes, it reads the stored mnemonic to open the wallet. Sometimes the read returns nothing or fails even though the wallet is still on the device, causing the app to create a new wallet in its place. To avoid this:

* **Generate a mnemonic in your create flow only:** Never generate one because a read came back empty. On Android, `expo-secure-store` returns `null` after it deletes an entry whose Keystore key is missing. A new mnemonic never opens the user's existing wallet.
* **Check for an existing entry before you create one:** On iOS, a keychain entry can survive an uninstall. If your create flow finds one, offer to restore that wallet. Delete the entry only once the user confirms they no longer need that wallet.
* **Retry on the next wake:** Skip the pass and read again on the next wake or foreground open. Never delete or overwrite the entry because a read failed. On iOS, a read before the first unlock after a restart fails with `errSecInteractionNotAllowed`.
* **Reopen with `createIfNotExists: false`:** Use it everywhere except your create and restore flows (`create_if_not_exists` in Rust, `CreateIfNotExists` in Go). With `true`, the default everywhere except Go, `Wallet.open()` creates a new wallet when it finds no stored wallet to open. With a wrong mnemonic, that new wallet is empty.

> [accordion] How Bark Wallet does it
>
> The web version runs the SDK in the browser, so the mnemonic stays there:
>
> * **Default:** AES-GCM under a non-extractable key stored in IndexedDB, with the ciphertext in `localStorage`. The wallet unlocks on reload without a prompt. A copy of `localStorage` alone can't reveal the mnemonic. A script running on the page or a copy of the whole browser profile can.
> * **With a password:** Once the user sets one under **Password protection** in Settings, the key comes from PBKDF2 (600,000 iterations) instead, and the wallet asks for the password on every load.
> * **Reopen:** `createIfNotExists: false`, so a wrong mnemonic fails instead of opening an empty wallet.
>
> A self-hosted install (Umbrel, Start9, or Docker) runs on Barkd, so the browser never stores the mnemonic:
>
> * **Storage:** Barkd stores the mnemonic in its data directory, as on any Barkd deployment.
> * **Reveal:** Bark Wallet runs `barkd` with `--expose-mnemonic`. Its API server fetches `GET /api/v1/wallet/mnemonic` from an endpoint that requires a session when `UI_AUTH` is on, and its barkd proxy blocks that route from the browser.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.