NyaruCrypto
public enum NyaruCrypto
Provides cryptographic helpers for generating and deriving database encryption keys.
Use NyaruCrypto to:
- Generate a random 256-bit AES key with
generateRandomKey()(store the result in the iOS Keychain). - Generate a random salt with
generateSalt()(persist the salt alongside the database — it is not secret). - 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() -> SymmetricKeyReturn Value
A new random
SymmetricKeyof 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) -> DataParameters
byteCountThe 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
NyaruErrorif key derivation fails.Declaration
Swift
public static func deriveKey( fromPassword password: String, salt: Data, using algorithm: KeyDerivationAlgorithm = .pbkdf2sha256() ) throws -> SymmetricKeyParameters
passwordThe password or secret string.
saltA salt value (generated with
generateSalt()), persisted alongside the database.algorithmThe key derivation algorithm (defaults to PBKDF2-SHA256 with 210,000 iterations).
Return Value
A 256-bit AES symmetric key.
View on GitHub