NyaruCrypto

public enum NyaruCrypto

Provides cryptographic helpers for generating and deriving database encryption keys.

Use NyaruCrypto to:

  1. Generate a random 256-bit AES key with generateRandomKey() (store the result in the iOS Keychain).
  2. Generate a random salt with generateSalt() (persist the salt alongside the database — it is not secret).
  3. Derive an encryption key from a password with deriveKey(fromPassword:salt:using:).

The derived or generated key is then passed to DatabaseOptions as the encryptionKey parameter.

  • Generates a cryptographically random 256-bit AES symmetric key.

    Call this once during initial setup, store the returned key in the system Keychain, and pass it to DatabaseOptions(encryptionKey:) every time the database is opened.

    Declaration

    Swift

    public static func generateRandomKey() -> SymmetricKey

    Return Value

    A new random SymmetricKey of length 32 bytes (256 bits).

  • Generates a cryptographically random salt value for key derivation.

    The salt should be persisted alongside the database files — it is not secret and does not need protection. A new salt should be generated for each database instance.

    Declaration

    Swift

    public static func generateSalt(byteCount: Int = 16) -> Data

    Parameters

    byteCount

    The length of the salt in bytes (default 16).

    Return Value

    Random salt data.

  • Derives a 256-bit AES symmetric key from a password or secret using the specified algorithm.

    Use PBKDF2 when the input is a user-memorable password (low entropy) and HKDF when the input is already cryptographically random (high entropy).

    Throws

    NyaruError if key derivation fails.

    Declaration

    Swift

    public static func deriveKey(
      fromPassword password: String,
      salt: Data,
      using algorithm: KeyDerivationAlgorithm = .pbkdf2sha256()
    ) throws -> SymmetricKey

    Parameters

    password

    The password or secret string.

    salt

    A salt value (generated with generateSalt()), persisted alongside the database.

    algorithm

    The key derivation algorithm (defaults to PBKDF2-SHA256 with 210,000 iterations).

    Return Value

    A 256-bit AES symmetric key.