Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Move PIN unlock and AES crypto call logic to Rust core
Leendert de Borst3f82d065d4b0
diff --git a/apps/browser-extension/src/utils/PinUnlockService.ts b/apps/browser-extension/src/utils/PinUnlockService.tsindex b28b9dedf..ffc0c1021 100644--- a/apps/browser-extension/src/utils/PinUnlockService.ts+++ b/apps/browser-extension/src/utils/PinUnlockService.ts@@ -1,4 +1,4 @@-import { argon2DeriveKey } from '@aliasvault/client/rust/RustCore';+import { pinDecrypt, pinEncrypt, pinGenerateSalt, pinIsLocked, pinRegisterFailure } from '@aliasvault/client/rust/RustCore';import { base64ToBytes, bytesToBase64 } from '@aliasvault/client/utilities/Base64';import { PIN_STORAGE_KEYS, StorageKeys } from '@/utils/constants/storageKeys';@@ -29,10 +29,11 @@ import { browser, storage } from '#imports';** Recommendation: Use PIN unlock only on trusted devices. For high-security scenarios, always* use full master password unlock.+ *+ * The key wrap and the attempt policy live in the Rust core (crypto/pin.rs); this file only stores them.+ * Other platform implementations: VaultStore+Pin.swift (iOS), VaultPin.kt (Android).*/-const MAX_PIN_ATTEMPTS = 4;-/*** Error thrown when PIN is locked after too many failed attempts.* Translation key: settings.unlockMethod.pinLocked@@ -126,18 +127,17 @@ export function isValidPin(pin: string): boolean {}/**- * Get failed attempts count.+ * Get the failed attempts count, or null when the stored counter is unreadable (which counts as locked).*/-export async function getFailedAttempts(): Promise<number> {+async function getFailedAttempts(): Promise<number | null> {try {const result = await storage.getItem(StorageKeys.PIN_FAILED_ATTEMPTS);if (result === null || result === undefined) {return 0;}- return Number.isInteger(result) && (result as number) >= 0 ? result as number : MAX_PIN_ATTEMPTS;+ return Number.isInteger(result) && (result as number) >= 0 ? result as number : null;} catch {- // Failure to retrieve the counter counts as the maximum for safety reasons.- return MAX_PIN_ATTEMPTS;+ return null;}}@@ -146,7 +146,7 @@ export async function getFailedAttempts(): Promise<number> {*/export async function isPinLocked(): Promise<boolean> {const attempts = await getFailedAttempts();- return attempts >= MAX_PIN_ATTEMPTS;+ return attempts === null || await pinIsLocked(attempts);}/**@@ -162,27 +162,9 @@ export async function setupPin(pin: string, accountKey: string): Promise<void> {}try {- // Generate random salt- const salt = crypto.getRandomValues(new Uint8Array(16));+ const salt = await pinGenerateSalt();const saltBase64 = bytesToBase64(salt);-- // Derive key from PIN using Argon2id- const combinedSalt = await assembleSaltWithPepper(salt);- const pinKey = await derivePinKey(pin, combinedSalt);-- // Encrypt the Account Key- const iv = crypto.getRandomValues(new Uint8Array(12));- const encryptedKey = await crypto.subtle.encrypt(- { name: 'AES-GCM', iv },- pinKey,- new TextEncoder().encode(accountKey)- );-- // Combine IV + encrypted data- const combined = new Uint8Array(iv.length + encryptedKey.byteLength);- combined.set(iv, 0);- combined.set(new Uint8Array(encryptedKey), iv.length);- const encryptedKeyBase64 = bytesToBase64(combined);+ const encryptedKeyBase64 = bytesToBase64(await pinEncrypt(pin, await argon2Salt(salt), new TextEncoder().encode(accountKey)));/* Store encrypted key, salt, PIN length, and enable flag */await Promise.all([@@ -217,7 +199,8 @@ export async function unlockWithPin(pin: string): Promise<string> {}/* Check if locked due to too many attempts */- if (await isPinLocked()) {+ const failedAttempts = await getFailedAttempts();+ if (failedAttempts === null || await pinIsLocked(failedAttempts)) {throw new PinLockedError();}@@ -232,23 +215,7 @@ export async function unlockWithPin(pin: string): Promise<string> {throw new PinLockedError();}- // Decode encrypted package- const combined = base64ToBytes(encryptedKeyBase64);- const iv = combined.slice(0, 12);- const encryptedData = combined.slice(12);-- // Derive key from PIN with extension ID pepper- const salt = base64ToBytes(saltBase64);- const combinedSalt = await assembleSaltWithPepper(salt);- const pinKey = await derivePinKey(pin, combinedSalt);-- // Decrypt the stored key- const decryptedData = await crypto.subtle.decrypt(- { name: 'AES-GCM', iv },- pinKey,- encryptedData- );-+ const decryptedData = await pinDecrypt(pin, await argon2Salt(base64ToBytes(saltBase64)), base64ToBytes(encryptedKeyBase64));const unlockKey = new TextDecoder().decode(decryptedData);/* Reset failed attempts on success */@@ -256,21 +223,19 @@ export async function unlockWithPin(pin: string): Promise<string> {return unlockKey;} catch {- /* Increment failed attempts */- const currentAttempts = await getFailedAttempts();- const newAttempts = currentAttempts + 1;- await storage.setItem(StorageKeys.PIN_FAILED_ATTEMPTS, newAttempts);+ const failure = await pinRegisterFailure(failedAttempts);+ await storage.setItem(StorageKeys.PIN_FAILED_ATTEMPTS, failure.failedAttempts);/** If max attempts reached, disable PIN and clear ALL stored data for security.* This prevents offline brute-force attacks on the encrypted key.*/- if (newAttempts >= MAX_PIN_ATTEMPTS) {+ if (failure.locked) {await removeAndDisablePin();throw new PinLockedError();}- throw new IncorrectPinError(MAX_PIN_ATTEMPTS - newAttempts);+ throw new IncorrectPinError(failure.attemptsRemaining);}}@@ -320,52 +285,17 @@ async function getExtensionPepper(): Promise<Uint8Array> {}/**- * Combine random salt with extension ID pepper+ * The Argon2id salt for the PIN key: the UTF-8 characters of base64(random salt || extension ID pepper).*- * Creates a composite salt that includes both:- * 1. Random salt (stored locally, prevents rainbow tables)- * 2. Extension ID pepper (not stored, prevents offline brute-force)+ * The salt is hashed as the characters of this base64 string, not as the bytes it decodes to.+ * Every PIN ever set was derived that way, so decoding here would lock users out of their vault.** @param randomSalt - The random salt stored in chrome.storage- * @returns Combined salt for Argon2id key derivation*/-async function assembleSaltWithPepper(randomSalt: Uint8Array): Promise<Uint8Array> {+async function argon2Salt(randomSalt: Uint8Array): Promise<Uint8Array> {const pepper = await getExtensionPepper();-- // Combine: random_salt || extension_id_pepperconst combinedSalt = new Uint8Array(randomSalt.length + pepper.length);combinedSalt.set(randomSalt, 0);combinedSalt.set(pepper, randomSalt.length);-- return combinedSalt;-}--/**- * Argon2id cost parameters for PIN key derivation.- */-const PIN_ARGON2_SETTINGS = '{"MemorySize":65536,"Iterations":3,"DegreeOfParallelism":1}';--/**- * Derive encryption key from PIN using Argon2id- */-async function derivePinKey(pin: string, salt: Uint8Array): Promise<CryptoKey> {- /*- * The salt is hashed as the characters of this base64 string, not as the bytes it decodes to.- * Every PIN ever set was derived that way, so decoding here would lock users out of their vault.- */- const saltBase64 = bytesToBase64(salt);-- // Derive key using Argon2id, stating the PIN cost parameters instead of the account's- const hash = await argon2DeriveKey(pin, saltBase64, PIN_ARGON2_SETTINGS);-- // Import the derived key into WebCrypto API- const pinKey = await crypto.subtle.importKey(- 'raw',- hash,- { name: 'AES-GCM', length: 256 },- false,- ['encrypt', 'decrypt']- );-- return pinKey;+ return new TextEncoder().encode(bytesToBase64(combinedSalt));}diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/RustCoreDispatcher.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/RustCoreDispatcher.ktindex ffa363f3e..08a10fa52 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/RustCoreDispatcher.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/RustCoreDispatcher.kt@@ -35,6 +35,9 @@ import uniffi.aliasvault_core.srpDeriveVerifierimport uniffi.aliasvault_core.srpGenerateEphemeralimport uniffi.aliasvault_core.srpGenerateSaltimport uniffi.aliasvault_core.srpVerifySession+import uniffi.aliasvault_core.symmetricDecrypt+import uniffi.aliasvault_core.symmetricDecryptBytes+import uniffi.aliasvault_core.symmetricEncryptBytesimport uniffi.aliasvault_core.vaultCodecCanonicalizeFromSqliteimport uniffi.aliasvault_core.vaultCodecGenerateManifestSaltimport uniffi.aliasvault_core.vaultCodecLogoContentHash@@ -83,6 +86,9 @@ object RustCoreDispatcher {"decodeEmailSource" -> json(decodeEmailSource(args.bytes(0)))"extractEmailAttachment" -> json(extractEmailAttachment(args.bytes(0), args.uint(1), args.optionalBytes(2)))"rsaDecrypt" -> json(rsaDecrypt(args.string(0), args.string(1)))+ "symmetricEncryptBytes" -> json(symmetricEncryptBytes(args.bytes(0), args.string(1)))+ "symmetricDecrypt" -> json(symmetricDecrypt(args.string(0), args.string(1)))+ "symmetricDecryptBytes" -> json(symmetricDecryptBytes(args.bytes(0), args.string(1)))"argon2DeriveKey" -> json(argon2DeriveKey(args.string(0), args.string(1), args.string(2)))"deriveSrpPasswordHash" -> json(deriveSrpPasswordHash(args.bytes(0), args.string(1)))diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultPin.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultPin.ktindex 668b0361e..7326839ea 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultPin.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultPin.kt@@ -7,13 +7,16 @@ import android.security.keystore.KeyPropertiesimport android.util.Base64import android.util.Logimport org.json.JSONObject+import uniffi.aliasvault_core.pinDecrypt+import uniffi.aliasvault_core.pinEncrypt+import uniffi.aliasvault_core.pinGenerateSalt+import uniffi.aliasvault_core.pinIsLocked+import uniffi.aliasvault_core.pinRegisterFailureimport java.security.KeyStore-import java.security.SecureRandomimport javax.crypto.Cipherimport javax.crypto.KeyGeneratorimport javax.crypto.SecretKeyimport javax.crypto.spec.GCMParameterSpec-import javax.crypto.spec.SecretKeySpec/*** Exception types for PIN unlock operations.@@ -41,6 +44,8 @@ sealed class PinUnlockException(message: String) : Exception(message) {* Handles PIN unlock functionality for the vault store.* This component manages PIN-based unlocking by encrypting the Account Key* with a key derived from the user's PIN using Argon2id.+ * The key wrap and the attempt policy live in the Rust core (crypto/pin.rs); this class only stores them.+ * Other platform implementations: VaultStore+Pin.swift (iOS), PinUnlockService.ts (browser extension).** Security features:* - 4 failed attempts maximum before requiring full password@@ -63,11 +68,6 @@ class VaultPin(*/private const val TAG = "VaultPin"- /**- * The maximum number of failed PIN attempts before locking.- */- private const val MAX_PIN_ATTEMPTS = 4-/*** Shared preferences keys for PIN metadata (non-sensitive data only).*/@@ -82,12 +82,7 @@ class VaultPin(private const val KEYSTORE_ALIAS_DATA_ENCRYPTION = "aliasvault_pin_data_encryption_key"/**- * Argon2id settings for PIN unlock.- */- private const val ARGON2_SETTINGS = """{"MemorySize":65536,"Iterations":3,"DegreeOfParallelism":1}"""-- /**- * AES-GCM parameters.+ * AES-GCM parameters of the Keystore-encrypted storage.*/private const val GCM_IV_LENGTH = 12private const val GCM_TAG_LENGTH = 128@@ -114,16 +109,15 @@ class VaultPin(}/**- * Get failed attempts count from secure storage (Android Keystore).- * @return The number of failed PIN attempts+ * Get the failed attempts count from secure storage (Android Keystore).+ * @return The number of failed PIN attempts, or null when the counter is unreadable (which counts as locked)*/- fun getPinFailedAttempts(): Int {+ private fun getPinFailedAttempts(): UInt? {return try {retrievePinFailedAttemptsFromKeystore()} catch (e: Exception) {- // Failure to retrieve the counter counts as the maximum for safety reasons.Log.e(TAG, "Failed to retrieve failed attempts, treating PIN as locked", e)- MAX_PIN_ATTEMPTS+ null}}@@ -141,32 +135,11 @@ class VaultPin(@Throws(Exception::class)fun setupPin(pin: String, accountKeyBase64: String) {val accountKey = Base64.decode(accountKeyBase64, Base64.NO_WRAP)-- // Generate random salt- val salt = ByteArray(16)- SecureRandom().nextBytes(salt)-- // Derive key from PIN + salt using Argon2id- val pinKey = derivePinKey(pin, salt)-- // Encrypt the Account Key using AES-GCM- val cipher = Cipher.getInstance("AES/GCM/NoPadding")- val secretKey = SecretKeySpec(pinKey, "AES")-- // Generate random IV for AES-GCM- val iv = ByteArray(GCM_IV_LENGTH)- SecureRandom().nextBytes(iv)-- cipher.init(Cipher.ENCRYPT_MODE, secretKey, GCMParameterSpec(GCM_TAG_LENGTH, iv))- val encryptedKey = cipher.doFinal(accountKey)-- // Combine IV + encrypted data- val combined = ByteArray(iv.size + encryptedKey.size)- System.arraycopy(iv, 0, combined, 0, iv.size)- System.arraycopy(encryptedKey, 0, combined, iv.size, encryptedKey.size)+ val salt = pinGenerateSalt()+ val encryptedKey = pinEncrypt(pin, salt, accountKey)// Store encrypted key and salt in Android Keystore- storePinDataInKeystore(combined, salt)+ storePinDataInKeystore(encryptedKey, salt)// Initialize failed attempts counter in KeystorestorePinFailedAttemptsInKeystore(0)@@ -194,27 +167,15 @@ class VaultPin(@Throws(PinUnlockException::class)@Suppress("SwallowedException") // We intentionally swallow to avoid exposing crypto implementation detailsfun unlockWithPin(pin: String): String {- if (getPinFailedAttempts() >= MAX_PIN_ATTEMPTS) {+ val failedAttempts = getPinFailedAttempts()+ if (failedAttempts == null || pinIsLocked(failedAttempts)) {removeAndDisablePin()throw PinUnlockException.Locked}try {- // Retrieve encrypted key and salt from Keystoreval (encryptedKey, salt) = retrievePinDataFromKeystore()-- // Decode encrypted package- val iv = encryptedKey.copyOfRange(0, GCM_IV_LENGTH)- val encryptedData = encryptedKey.copyOfRange(GCM_IV_LENGTH, encryptedKey.size)-- // Derive key from PIN + salt- val pinKey = derivePinKey(pin, salt)-- // Decrypt the PIN-protected key- val cipher = Cipher.getInstance("AES/GCM/NoPadding")- val secretKey = SecretKeySpec(pinKey, "AES")- cipher.init(Cipher.DECRYPT_MODE, secretKey, GCMParameterSpec(GCM_TAG_LENGTH, iv))- val decryptedKey = cipher.doFinal(encryptedData)+ val decryptedKey = pinDecrypt(pin, salt, encryptedKey)// Reset failed attempts on successstorePinFailedAttemptsInKeystore(0)@@ -222,20 +183,16 @@ class VaultPin(// Return the decrypted key as base64return Base64.encodeToString(decryptedKey, Base64.NO_WRAP)} catch (e: Exception) {- // Increment failed attempts- val currentAttempts = getPinFailedAttempts()- val newAttempts = currentAttempts + 1- storePinFailedAttemptsInKeystore(newAttempts)+ val failure = pinRegisterFailure(failedAttempts)+ storePinFailedAttemptsInKeystore(failure.failedAttempts.toInt())// If max attempts reached, disable PIN and clear all stored data- if (newAttempts >= MAX_PIN_ATTEMPTS) {+ if (failure.locked) {removeAndDisablePin()throw PinUnlockException.Locked}- // Return incorrect PIN error with attempts remaining- val attemptsRemaining = MAX_PIN_ATTEMPTS - newAttempts- throw PinUnlockException.IncorrectPin(attemptsRemaining)+ throw PinUnlockException.IncorrectPin(failure.attemptsRemaining.toInt())}}@@ -277,29 +234,6 @@ class VaultPin(// MARK: - Private PIN Methods- /**- * Derive encryption key from PIN + salt using Argon2id.- *- * Uses Argon2id with high memory cost (64 MB) to make brute-force attacks expensive.- * The salt is stored in Android Keystore with device-unlock protection, which means- * an attacker who steals the encrypted blob cannot brute-force offline because they- * cannot access the salt without unlocking the device.- *- * @param pin User's PIN (low entropy)- * @param salt Random salt (stored in Keystore, requires device unlock to access)- * @return The derived key bytes (32 bytes)- * @throws Exception if key derivation fails- */- @Throws(Exception::class)- private fun derivePinKey(pin: String, salt: ByteArray): ByteArray {- try {- return uniffi.aliasvault_core.argon2DeriveKeyBytes(pin.toByteArray(Charsets.UTF_8), salt, ARGON2_SETTINGS)- } catch (e: Exception) {- Log.e(TAG, "Argon2 PIN hashing failed", e)- throw Exception("Argon2 PIN hashing failed", e)- }- }-// MARK: - PIN Data Storage (Encrypted Key + Salt)/**@@ -410,37 +344,33 @@ class VaultPin(* Retrieve failed attempts counter from Android Keystore.*/@Throws(Exception::class)- private fun retrievePinFailedAttemptsFromKeystore(): Int {+ private fun retrievePinFailedAttemptsFromKeystore(): UInt {// Get encrypted data from SharedPreferencesval combinedBase64 = sharedPreferences.getString(KEYSTORE_ALIAS_FAILED_ATTEMPTS, null)- ?: return 0 // Default if not found+ ?: return 0u // Default if not found- try {- val combined = Base64.decode(combinedBase64, Base64.NO_WRAP)- val iv = combined.copyOfRange(0, GCM_IV_LENGTH)- val encryptedData = combined.copyOfRange(GCM_IV_LENGTH, combined.size)-- // Get decryption key from Keystore- val secretKey = keyStore.getKey(KEYSTORE_ALIAS_DATA_ENCRYPTION, null) as? SecretKey- ?: return MAX_PIN_ATTEMPTS-- // Decrypt the attempts data- val cipher = Cipher.getInstance("AES/GCM/NoPadding")- cipher.init(Cipher.DECRYPT_MODE, secretKey, GCMParameterSpec(GCM_TAG_LENGTH, iv))- val decryptedData = cipher.doFinal(encryptedData)- if (decryptedData.size != 4) {- return MAX_PIN_ATTEMPTS- }+ val combined = Base64.decode(combinedBase64, Base64.NO_WRAP)+ val iv = combined.copyOfRange(0, GCM_IV_LENGTH)+ val encryptedData = combined.copyOfRange(GCM_IV_LENGTH, combined.size)- // Convert ByteArray to Int- return ((decryptedData[0].toInt() and 0xFF) shl 24) or- ((decryptedData[1].toInt() and 0xFF) shl 16) or- ((decryptedData[2].toInt() and 0xFF) shl 8) or- (decryptedData[3].toInt() and 0xFF)- } catch (e: Exception) {- Log.e(TAG, "Failed to decode failed attempts, treating PIN as locked", e)- return MAX_PIN_ATTEMPTS+ // Get decryption key from Keystore+ val secretKey = keyStore.getKey(KEYSTORE_ALIAS_DATA_ENCRYPTION, null) as? SecretKey+ ?: throw Exception("Keystore key for PIN attempts not found")++ // Decrypt the attempts data+ val cipher = Cipher.getInstance("AES/GCM/NoPadding")+ cipher.init(Cipher.DECRYPT_MODE, secretKey, GCMParameterSpec(GCM_TAG_LENGTH, iv))+ val decryptedData = cipher.doFinal(encryptedData)+ if (decryptedData.size != 4) {+ throw Exception("Invalid PIN failed attempts value")}++ // Convert ByteArray to Int+ val attempts = ((decryptedData[0].toInt() and 0xFF) shl 24) or+ ((decryptedData[1].toInt() and 0xFF) shl 16) or+ ((decryptedData[2].toInt() and 0xFF) shl 8) or+ (decryptedData[3].toInt() and 0xFF)+ return attempts.toUInt()}/**diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStore.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStore.ktindex 7a4fab087..0c3ab786e 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStore.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStore.kt@@ -940,13 +940,6 @@ class VaultStore(return pin.getPinLength()}- /**- * Get failed PIN attempts count.- */- fun getPinFailedAttempts(): Int {- return pin.getPinFailedAttempts()- }-/*** Setup PIN unlock.*/diff --git a/apps/mobile-app/app/(tabs)/emails/[id].tsx b/apps/mobile-app/app/(tabs)/emails/[id].tsxindex a2e067b2d..0a6af75b3 100644--- a/apps/mobile-app/app/(tabs)/emails/[id].tsx+++ b/apps/mobile-app/app/(tabs)/emails/[id].tsx@@ -1,5 +1,6 @@import { Buffer } from 'buffer';+import EncryptionUtility, { type DecryptedEmail } from '@aliasvault/client/crypto/EncryptionUtility';import { decodeEmailSource, extractEmailAttachment, type ParsedEmailAttachment } from '@aliasvault/client/rust/RustCore';import { Ionicons } from '@expo/vector-icons';import { Paths } from 'expo-file-system';@@ -12,7 +13,6 @@ import { WebView, type WebViewNavigation } from 'react-native-webview';import ConversionUtility from '@/utils/ConversionUtility';import type { DisplayItem } from '@/utils/DisplayItem';-import EncryptionUtility, { type DecryptedEmail } from '@/utils/EncryptionUtility';import emitter from '@/utils/EventEmitter';import { getFileForFilename } from '@/utils/FileUtility';import { itemRoute } from '@/utils/ItemRoute';diff --git a/apps/mobile-app/app/(tabs)/emails/index.tsx b/apps/mobile-app/app/(tabs)/emails/index.tsxindex 18e0fc53a..019414ef9 100644--- a/apps/mobile-app/app/(tabs)/emails/index.tsx+++ b/apps/mobile-app/app/(tabs)/emails/index.tsx@@ -1,3 +1,4 @@+import EncryptionUtility from '@aliasvault/client/crypto/EncryptionUtility';import { useNavigation } from 'expo-router';import React, { useEffect, useState, useCallback, useRef } from 'react';import { useTranslation } from 'react-i18next';@@ -5,7 +6,6 @@ import { StyleSheet, Platform, View, ScrollView, RefreshControl, Animated, Touchimport { useSafeAreaInsets } from 'react-native-safe-area-context';import Toast from 'react-native-toast-message';-import EncryptionUtility from '@/utils/EncryptionUtility';import emitter from '@/utils/EventEmitter';import { HapticsUtility } from '@/utils/HapticsUtility';diff --git a/apps/mobile-app/app/login.tsx b/apps/mobile-app/app/login.tsxindex a830bc657..f9ffe83d7 100644--- a/apps/mobile-app/app/login.tsx+++ b/apps/mobile-app/app/login.tsx@@ -1,5 +1,3 @@-import { Buffer } from 'buffer';-import { describeAuthError, formatErrorMessage } from '@aliasvault/client/auth/AuthErrorMessage';import { SrpAuthService, type PreparedCredentials } from '@aliasvault/client/auth/SrpAuthService';import { SrpLoginService } from '@aliasvault/client/auth/SrpLoginService';@@ -12,7 +10,6 @@ import { SafeAreaView } from 'react-native-safe-area-context';import { useApiUrl } from '@/utils/ApiUrlUtility';import { AppUnlockUtility } from '@/utils/AppUnlockUtility';-import EncryptionUtility from '@/utils/EncryptionUtility';import { LocalAuthError } from '@/utils/types/errors/LocalAuthError';import { useColors } from '@/hooks/useColorScheme';@@ -371,14 +368,7 @@ export default function LoginScreen() : React.ReactNode {try {const initiateLoginResponse = await srpUtil.initiateLogin(SrpAuthService.normalizeUsername(credentials.username));- const unlockKey = await EncryptionUtility.deriveKeyFromPassword(- credentials.password,- initiateLoginResponse.salt,- initiateLoginResponse.encryptionType,- initiateLoginResponse.encryptionSettings- );-- const unlockKeyBase64 = Buffer.from(unlockKey).toString('base64');+ const unlockKeyBase64 = await NativeVaultManager.deriveKeyFromPassword(credentials.password, initiateLoginResponse.salt, initiateLoginResponse.encryptionType, initiateLoginResponse.encryptionSettings);const passwordCredentials = await SrpAuthService.loginCredentials(unlockKeyBase64, initiateLoginResponse, credentials.username);setLoginStatus(t('auth.validatingCredentials'));diff --git a/apps/mobile-app/components/items/details/EmailPreview.tsx b/apps/mobile-app/components/items/details/EmailPreview.tsxindex dc44a0cd4..791d9853b 100644--- a/apps/mobile-app/components/items/details/EmailPreview.tsx+++ b/apps/mobile-app/components/items/details/EmailPreview.tsx@@ -12,7 +12,7 @@ import { AppInfo } from '@aliasvault/client/platform/AppInfo';import { logExpected } from '@aliasvault/client/utilities/Diagnostics';import { mailboxPollDelayMs } from '@aliasvault/client/utilities/PollBackoff';import type { ApiErrorResponse, Mailbox, MailboxEmail } from '@aliasvault/models/webapi';-import EncryptionUtility from '@/utils/EncryptionUtility';+import EncryptionUtility from '@aliasvault/client/crypto/EncryptionUtility';import { useColors } from '@/hooks/useColorScheme';diff --git a/apps/mobile-app/context/AuthContext.tsx b/apps/mobile-app/context/AuthContext.tsxindex d85d3a707..680f1c48d 100644--- a/apps/mobile-app/context/AuthContext.tsx+++ b/apps/mobile-app/context/AuthContext.tsx@@ -1,8 +1,6 @@-import { Buffer } from 'buffer';import AsyncStorage from '@react-native-async-storage/async-storage';import React, { createContext, useContext, useState, useEffect, useMemo, useCallback } from 'react';-import EncryptionUtility from '@/utils/EncryptionUtility';import type { AuthMethod } from '@/utils/AppUnlockUtility';import { useDb } from '@/context/DbContext';@@ -259,14 +257,7 @@ export const AuthProvider: React.FC<{}// Derive the unlock key from the password using the stored parameters- const unlockKey = await EncryptionUtility.deriveKeyFromPassword(- password,- params.salt,- params.encryptionType,- params.encryptionSettings- );-- const unlockKeyBase64 = Buffer.from(unlockKey).toString('base64');+ const unlockKeyBase64 = await NativeVaultManager.deriveKeyFromPassword(password, params.salt, params.encryptionType, params.encryptionSettings);// Check if the current password is correctconst isValid = await dbContext.verifyUnlockKey(unlockKeyBase64);diff --git a/apps/mobile-app/ios/NativeVaultManager/NativeVaultManager.swift b/apps/mobile-app/ios/NativeVaultManager/NativeVaultManager.swiftindex 7d7804566..ec70ea2ae 100644--- a/apps/mobile-app/ios/NativeVaultManager/NativeVaultManager.swift+++ b/apps/mobile-app/ios/NativeVaultManager/NativeVaultManager.swift@@ -1547,6 +1547,9 @@ private enum RustCoreDispatcher {case "extractEmailAttachment":return try json(bytes: try RustCoreFramework.extractEmailAttachment(source: try args.data(0), index: try args.uint32(1), detachedBody: try args.optionalData(2)))case "rsaDecrypt": return try json(bytes: try RustCoreFramework.rsaDecrypt(base64Ciphertext: try args.string(0), privateKeyJwk: try args.string(1)))+ case "symmetricEncryptBytes": return try json(bytes: try RustCoreFramework.symmetricEncryptBytes(plaintext: try args.data(0), keyBase64: try args.string(1)))+ case "symmetricDecrypt": return try json(try RustCoreFramework.symmetricDecrypt(base64Ciphertext: try args.string(0), keyBase64: try args.string(1)))+ case "symmetricDecryptBytes": return try json(bytes: try RustCoreFramework.symmetricDecryptBytes(encrypted: try args.data(0), keyBase64: try args.string(1)))case "argon2DeriveKey":return try json(bytes: try RustCoreFramework.argon2DeriveKey(password: try args.string(0), salt: try args.string(1), encryptionSettings: try args.string(2)))diff --git a/apps/mobile-app/ios/Podfile.lock b/apps/mobile-app/ios/Podfile.lockindex 4eb1a9cdb..a457b40a8 100644--- a/apps/mobile-app/ios/Podfile.lock+++ b/apps/mobile-app/ios/Podfile.lock@@ -1512,8 +1512,6 @@ PODS:- ReactCommon/turbomodule/core- ReactNativeDependencies- Yoga- - react-native-aes-gcm-crypto (0.2.2):- - React-Core- react-native-context-menu-view (1.21.0):- React- react-native-get-random-values (1.11.0):@@ -2393,7 +2391,6 @@ DEPENDENCIES:- React-Mapbuffer (from `../node_modules/react-native/ReactCommon`)- React-microtasksnativemodule (from `../node_modules/react-native/ReactCommon/react/nativemodule/microtasks`)- React-mutationobservernativemodule (from `../node_modules/react-native/ReactCommon/react/nativemodule/mutationobserver`)- - react-native-aes-gcm-crypto (from `../node_modules/react-native-aes-gcm-crypto`)- react-native-context-menu-view (from `../node_modules/react-native-context-menu-view`)- react-native-get-random-values (from `../node_modules/react-native-get-random-values`)- react-native-safe-area-context (from `../node_modules/react-native-safe-area-context`)@@ -2582,8 +2579,6 @@ EXTERNAL SOURCES::path: "../node_modules/react-native/ReactCommon/react/nativemodule/microtasks"React-mutationobservernativemodule::path: "../node_modules/react-native/ReactCommon/react/nativemodule/mutationobserver"- react-native-aes-gcm-crypto:- :path: "../node_modules/react-native-aes-gcm-crypto"react-native-context-menu-view::path: "../node_modules/react-native-context-menu-view"react-native-get-random-values:@@ -2745,7 +2740,6 @@ SPEC CHECKSUMS:React-Mapbuffer: fec3e025f0ffba6b32cd2a1d7bbdee3e269aae90React-microtasksnativemodule: ab33a818d339f5a1da308893c11b487be66121a8React-mutationobservernativemodule: a42d1626651ccd7d0dc02a56e69d4ec77c248893- react-native-aes-gcm-crypto: d572dd7a69f31c539bb8309b3a829bfa3bfad244react-native-context-menu-view: da39a4612c1294d651907162529cfba8421e9b89react-native-get-random-values: d16467cf726c618e9c7a8c3c39c31faa2244bbbareact-native-safe-area-context: 6b4966397ada0f7dd481e4486a2ef936834861a1diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Pin.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Pin.swiftindex ab3b286d9..b514e8f6e 100644--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Pin.swift+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Pin.swift@@ -1,11 +1,12 @@import Foundation-import CryptoKitimport Securityimport RustCoreFrameworkimport VaultModelsimport VaultUtils-/// Extension for the VaultStore class to handle PIN unlock functionality+/// Extension for the VaultStore class to handle PIN unlock functionality.+/// The key wrap and the attempt policy live in the Rust core (crypto/pin.rs); this file only stores them.+/// Other platform implementations: VaultPin.kt (Android), PinUnlockService.ts (browser extension).extension VaultStore {// MARK: - PIN Constants@@ -13,10 +14,6 @@ extension VaultStore {private static let pinSaltKey = "pinSalt"private static let pinLengthKey = "pinLength"private static let pinFailedAttemptsKey = "pinFailedAttempts"- private static let maxPinAttempts = 4-- /// Argon2id cost parameters for PIN key derivation.- private static let pinArgon2Settings = "{\"MemorySize\":65536,\"Iterations\":3,\"DegreeOfParallelism\":1}"// MARK: - PIN Status Methods@@ -32,14 +29,9 @@ extension VaultStore {return length > 0 ? length : nil}- /// Get failed attempts count from secure storage.- public func getPinFailedAttempts() -> Int {- do {- return try retrievePinFailedAttemptsFromKeychain()- } catch {- // Failure to retrieve the counter counts as the maximum for safety reasons.- return Self.maxPinAttempts- }+ /// Get the failed attempts count from secure storage, or nil when it is unreadable (which counts as locked).+ private func getPinFailedAttempts() -> UInt32? {+ return try? retrievePinFailedAttemptsFromKeychain()}// MARK: - PIN Setup Methods@@ -65,24 +57,8 @@ extension VaultStore {/// Encrypt the Account Key with a key derived from the PIN and keep it in the keychain.internal func encryptKeyWithPin(_ accountKey: Data, pin: String) throws {- // Generate random salt- var salt = Data(count: 16)- let result = salt.withUnsafeMutableBytes {- SecRandomCopyBytes(kSecRandomDefault, 16, $0.baseAddress!)- }- guard result == errSecSuccess else {- throw NSError(domain: "VaultStore", code: 22, userInfo: [NSLocalizedDescriptionKey: "Failed to generate random salt"])- }-- // Derive key from PIN + salt using Argon2id- let pinKey = try derivePinKey(pin: pin, salt: salt)-- // Encrypt the Account Key using AES-GCM- let symmetricKey = SymmetricKey(data: pinKey)- let sealedBox = try AES.GCM.seal(accountKey, using: symmetricKey)- guard let encryptedData = sealedBox.combined else {- throw NSError(domain: "VaultStore", code: 23, userInfo: [NSLocalizedDescriptionKey: "Failed to encrypt vault key"])- }+ let salt = RustCoreFramework.pinGenerateSalt()+ let encryptedData = try RustCoreFramework.pinEncrypt(pin: pin, salt: salt, secret: accountKey)// Store encrypted key and salt in keychain (without biometric protection)try storePinDataInKeychain(encryptedKey: encryptedData, salt: salt)@@ -113,22 +89,14 @@ extension VaultStore {/// Decrypt the key the PIN protects, counting a failure against the PIN attempts.private func decryptPinProtectedKey(_ pin: String) throws -> Data {- if getPinFailedAttempts() >= Self.maxPinAttempts {+ guard let failedAttempts = getPinFailedAttempts(), !RustCoreFramework.pinIsLocked(failedAttempts: failedAttempts) else {try? removeAndDisablePin()throw PinUnlockError.locked}do {- // Retrieve encrypted key and salt from keychainlet (encryptedKey, salt) = try retrievePinDataFromKeychain()-- // Derive key from PIN + salt- let pinKey = try derivePinKey(pin: pin, salt: salt)-- // Decrypt the vault encryption key- let symmetricKey = SymmetricKey(data: pinKey)- let sealedBox = try AES.GCM.SealedBox(combined: encryptedKey)- let decryptedKey = try AES.GCM.open(sealedBox, using: symmetricKey)+ let decryptedKey = try RustCoreFramework.pinDecrypt(pin: pin, salt: salt, encrypted: encryptedKey)// Reset failed attempts on successtry storePinFailedAttemptsInKeychain(0)@@ -136,20 +104,16 @@ extension VaultStore {return decryptedKey} catch {- // Increment failed attempts- let currentAttempts = getPinFailedAttempts()- let newAttempts = currentAttempts + 1- try? storePinFailedAttemptsInKeychain(newAttempts)+ let failure = RustCoreFramework.pinRegisterFailure(failedAttempts: failedAttempts)+ try? storePinFailedAttemptsInKeychain(Int(failure.failedAttempts))// If max attempts reached, disable PIN and clear all stored data- if newAttempts >= Self.maxPinAttempts {+ if failure.locked {try? removeAndDisablePin()throw PinUnlockError.locked}- // Return incorrect PIN error with attempts remaining- let attemptsRemaining = Self.maxPinAttempts - newAttempts- throw PinUnlockError.incorrectPin(attemptsRemaining: attemptsRemaining)+ throw PinUnlockError.incorrectPin(attemptsRemaining: Int(failure.attemptsRemaining))}}@@ -176,28 +140,6 @@ extension VaultStore {// MARK: - Private PIN Methods- /// Derive encryption key from PIN + salt using Argon2id- ///- /// Uses Argon2id with high memory cost (64 MB) to make brute-force attacks expensive.- /// The salt is stored in Keychain with device-unlock protection, which means an attacker- /// who steals the encrypted blob cannot brute-force offline because they cannot access- /// the salt without unlocking the device.- ///- /// Parameters:- /// - pin: User's PIN (low entropy)- /// - salt: Random salt (stored in Keychain, requires device unlock to access)- private func derivePinKey(pin: String, salt: Data) throws -> Data {- guard let pinData = pin.data(using: .utf8) else {- throw NSError(domain: "VaultStore", code: 28, userInfo: [NSLocalizedDescriptionKey: "Failed to convert PIN to data"])- }-- guard let derivedKey = try? RustCoreFramework.argon2DeriveKeyBytes(password: pinData, salt: salt, encryptionSettings: Self.pinArgon2Settings) else {- throw NSError(domain: "VaultStore", code: 29, userInfo: [NSLocalizedDescriptionKey: "Argon2 PIN hashing failed"])- }-- return derivedKey- }-/// Store PIN encrypted data in keychain (without biometric protection)private func storePinDataInKeychain(encryptedKey: Data, salt: Data) throws {// Create a dictionary to store both encrypted key and salt@@ -298,7 +240,7 @@ extension VaultStore {}/// Retrieve failed attempts counter from Keychain- private func retrievePinFailedAttemptsFromKeychain() throws -> Int {+ private func retrievePinFailedAttemptsFromKeychain() throws -> UInt32 {let query: [String: Any] = [kSecClass as String: kSecClassGenericPassword,kSecAttrService as String: VaultConstants.keychainService,@@ -320,10 +262,10 @@ extension VaultStore {}let attempts = data.withUnsafeBytes { $0.loadUnaligned(as: Int.self) }- guard attempts >= 0 else {+ guard attempts >= 0, let count = UInt32(exactly: attempts) else {throw NSError(domain: "VaultStore", code: 43, userInfo: [NSLocalizedDescriptionKey: "Invalid PIN failed attempts value"])}- return attempts+ return count}/// Remove failed attempts counter from Keychaindiff --git a/apps/mobile-app/package-lock.json b/apps/mobile-app/package-lock.jsonindex 1c8785588..66f7cd95e 100644--- a/apps/mobile-app/package-lock.json+++ b/apps/mobile-app/package-lock.json@@ -47,7 +47,6 @@"react-hook-form": "^7.56.1","react-i18next": "^16.6.6","react-native": "0.85.3",- "react-native-aes-gcm-crypto": "^0.2.2","react-native-context-menu-view": "^1.19.0","react-native-draggable-flatlist": "^4.0.3","react-native-edge-to-edge": "1.6.0",@@ -99,8 +98,7 @@"@aliasvault/models": "file:../models","@aliasvault/vault": "file:../vault","dompurify": "^3.4.12",- "fflate": "^0.8.3",- "otpauth": "^9.3.6"+ "fflate": "^0.8.3"},"devDependencies": {"@types/node": "^22.13.10",@@ -12527,16 +12525,6 @@}}},- "node_modules/react-native-aes-gcm-crypto": {- "version": "0.2.2",- "resolved": "https://registry.npmjs.org/react-native-aes-gcm-crypto/-/react-native-aes-gcm-crypto-0.2.2.tgz",- "integrity": "sha512-vUwkh2zBiIQMRY191IfZhDmhHVT+nV4sxet/A0V8J35lVShCA4kuFzBL+QVB06RM2EF8oZSnNMt/uvFkKAx6QQ==",- "license": "MIT",- "peerDependencies": {- "react": "*",- "react-native": "*"- }- },"node_modules/react-native-context-menu-view": {"version": "1.21.0","resolved": "https://registry.npmjs.org/react-native-context-menu-view/-/react-native-context-menu-view-1.21.0.tgz",diff --git a/apps/mobile-app/package.json b/apps/mobile-app/package.jsonindex 5d742526b..aee861aa2 100644--- a/apps/mobile-app/package.json+++ b/apps/mobile-app/package.json@@ -65,7 +65,6 @@"react-hook-form": "^7.56.1","react-i18next": "^16.6.6","react-native": "0.85.3",- "react-native-aes-gcm-crypto": "^0.2.2","react-native-context-menu-view": "^1.19.0","react-native-draggable-flatlist": "^4.0.3","react-native-edge-to-edge": "1.6.0",diff --git a/apps/mobile-app/platform/NativeRustCore.ts b/apps/mobile-app/platform/NativeRustCore.tsindex c87390811..ad0fe98b5 100644--- a/apps/mobile-app/platform/NativeRustCore.ts+++ b/apps/mobile-app/platform/NativeRustCore.ts@@ -26,6 +26,15 @@ function base64(bytes: Uint8Array): string {return Buffer.from(bytes).toString('base64');}+/**+ * Reject a core function that mobile JavaScript never calls because the native layer (Swift/Kotlin) runs it.+ */+function notImplementedOnMobile(name: string, reason: string): Promise<never> {+ return Promise.reject(new Error(`${name} is not implemented on mobile: ${reason}`));+}++const PIN_IS_NATIVE = 'PIN unlock runs in the native VaultStore';+/** The client core's Rust binding on mobile: the uniffi Swift/Kotlin bindings, reached through the one generic* `NativeVaultManager.rustCall` method. Swift and Kotlin hold a case per function and no logic. Functions that take a@@ -58,6 +67,17 @@ export const nativeRustCore: IRustCore = {decodeEmailSource: (source) => callForBytes('decodeEmailSource', base64(source)),extractEmailAttachment: (source, index, detachedBody) => callForBytes('extractEmailAttachment', base64(source), index, detachedBody ? base64(detachedBody) : null),+ symmetricEncryptBytes: (plaintext, keyBase64) => callForBytes('symmetricEncryptBytes', base64(plaintext), keyBase64),+ symmetricDecryptBytes: (encrypted, keyBase64) => callForBytes('symmetricDecryptBytes', base64(encrypted), keyBase64),+ symmetricDecrypt: (base64Ciphertext, keyBase64) => call('symmetricDecrypt', base64Ciphertext, keyBase64),+ rsaDecrypt: (base64Ciphertext, privateKeyJwk) => callForBytes('rsaDecrypt', base64Ciphertext, privateKeyJwk),++ pinGenerateSalt: () => notImplementedOnMobile('pinGenerateSalt', PIN_IS_NATIVE),+ pinEncrypt: () => notImplementedOnMobile('pinEncrypt', PIN_IS_NATIVE),+ pinDecrypt: () => notImplementedOnMobile('pinDecrypt', PIN_IS_NATIVE),+ pinIsLocked: () => notImplementedOnMobile('pinIsLocked', PIN_IS_NATIVE),+ pinRegisterFailure: () => notImplementedOnMobile('pinRegisterFailure', PIN_IS_NATIVE),+argon2DeriveKey: (password, salt, encryptionSettings) => callForBytes('argon2DeriveKey', password, salt, encryptionSettings),deriveSrpPasswordHash: (unlockKeyBase64, encryptionType) => call('deriveSrpPasswordHash', unlockKeyBase64, encryptionType),openAccountKeyChain: (storedKey, encryptedAccountKey, encryptedVek, encryptedAccountPrivateKey) => call('openAccountKeyChain', storedKey, encryptedAccountKey, encryptedVek, encryptedAccountPrivateKey),@@ -80,12 +100,6 @@ export const nativeRustCore: IRustCore = {vaultCodecPackPayload: (payloadJson) => callForBytes('vaultCodecPackPayload', payloadJson),vaultCodecUnpackPayload: (plainBytes) => call('vaultCodecUnpackPayload', base64(plainBytes)),- createVaultSyncSession: () => Promise.reject(new Error('The vault sync engine is driven natively on mobile and has no JavaScript session.')),+ createVaultSyncSession: () => notImplementedOnMobile('createVaultSyncSession', 'the vault sync engine is driven natively'),};-/**- * RSA-OAEP-256 decrypt base64 ciphertext with a JWK private key. Mobile only.- */-export function rsaDecrypt(base64Ciphertext: string, privateKeyJwk: string): Promise<Uint8Array> {- return callForBytes('rsaDecrypt', base64Ciphertext, privateKeyJwk);-}diff --git a/apps/mobile-app/utils/EncryptionUtility.ts b/apps/mobile-app/utils/EncryptionUtility.tsdeleted file mode 100644index 52df0f807..000000000--- a/apps/mobile-app/utils/EncryptionUtility.ts+++ /dev/null@@ -1,290 +0,0 @@-import { Buffer } from 'buffer';--import { gunzipSync, strFromU8 } from 'fflate';-import AesGcmCrypto from 'react-native-aes-gcm-crypto';--import { rsaDecrypt } from '@/platform/NativeRustCore';-import NativeVaultManager from '@/specs/NativeVaultManager';-import type { EncryptionKey } from '@aliasvault/models/vault';-import type { Email, EmailDecryptionKey, MailboxEmail } from '@aliasvault/models/webapi';-import { parseEmailSource, type ParsedEmailAttachment } from '@aliasvault/client/rust/RustCore';--/**- * An email after decryption: the metadata fields decrypted in place, and the bodies and attachments the Rust- * parser derived from the raw RFC 822 source.- */-export type DecryptedEmail = {- /** The email with its metadata fields decrypted. */- email: Email;- /** The html body parsed out of the source, null when the message has no html part. */- htmlBody: string | null;- /** The plain text body parsed out of the source, null when the message has no text part. */- textBody: string | null;- /** The attachments contained in the source, in the index order `extractEmailAttachment` expects. */- attachments: ParsedEmailAttachment[];- /** The decrypted source bytes. */- sourceBytes: Uint8Array | null;-};--/**- * Utility class for encryption operations including:- * - Argon2Id key derivation- * - AES-GCM symmetric encryption/decryption- * - RSA-OAEP asymmetric encryption/decryption- */-class EncryptionUtility {- /**- * Derives a key from a password using Argon2Id- */- public static async deriveKeyFromPassword(- password: string,- salt: string,- encryptionType: string,- encryptionSettings: string- ): Promise<Uint8Array> {- try {- // Call the native method to derive the key via Argon2id- const base64Key = await NativeVaultManager.deriveKeyFromPassword(- password,- salt,- encryptionType,- encryptionSettings- );-- // Convert base64 string to Uint8Array- const binaryString = atob(base64Key);- const bytes = new Uint8Array(binaryString.length);- for (let i = 0; i < binaryString.length; i++) {- bytes[i] = binaryString.charCodeAt(i);- }-- return bytes;- } catch (error) {- console.error('Argon2 hashing failed:', error);- throw error;- }- }-- /**- * Encrypts data using AES-GCM symmetric encryption- */- public static async symmetricEncrypt(plaintext: string, base64Key: string): Promise<string> {- if (!plaintext) {- return plaintext;- }-- try {- const result = await AesGcmCrypto.encrypt(plaintext, false, base64Key);- // Combine IV, tag, and content into a single string for storage- return JSON.stringify({- iv: result.iv,- tag: result.tag,- content: result.content- });- } catch (error) {- console.error('AES-GCM encryption failed:', error);- throw error;- }- }-- /**- * Decrypts data using AES-GCM symmetric encryption- */- public static async symmetricDecrypt(base64Ciphertext: string, base64Key: string): Promise<string> {- if (!base64Ciphertext) {- return base64Ciphertext;- }-- try {- const ciphertext = Uint8Array.from(atob(base64Ciphertext), c => c.charCodeAt(0));- const iv = ciphertext.slice(0, 12);- const tag = ciphertext.slice(-16);- const content = ciphertext.slice(12, -16);-- const contentBase64 = Buffer.from(content).toString('base64');- const ivHex = Buffer.from(iv).toString('hex');- const tagHex = Buffer.from(tag).toString('hex');-- const decryptedData = await AesGcmCrypto.decrypt(- contentBase64,- base64Key,- ivHex,- tagHex,- false- );- return decryptedData;- } catch (error) {- console.error('AES-GCM decryption failed:', error);- throw error;- }- }-- /**- * Decrypts data using AES-GCM symmetric encryption with raw bytes input/output- */- public static async symmetricDecryptBytes(encryptedBytes: Uint8Array, base64Key: string): Promise<Uint8Array> {- if (!encryptedBytes || encryptedBytes.length === 0) {- return encryptedBytes;- }-- const iv = encryptedBytes.slice(0, 12);- const tag = encryptedBytes.slice(-16);- const content = encryptedBytes.slice(12, -16);-- const decryptedBase64 = await AesGcmCrypto.decrypt(- Buffer.from(content).toString('base64'),- base64Key,- Buffer.from(iv).toString('hex'),- Buffer.from(tag).toString('hex'),- true- );- return new Uint8Array(Buffer.from(decryptedBase64, 'base64'));- }-- /**- * Decrypts a base64 AES-GCM payload that may be gzip compressed after decryption.- */- public static async symmetricDecryptMaybeCompressed(base64Ciphertext: string, base64Key: string): Promise<string> {- if (!base64Ciphertext) {- return base64Ciphertext;- }-- const encryptedBytes = Uint8Array.from(atob(base64Ciphertext), c => c.charCodeAt(0));- const decryptedBytes = await EncryptionUtility.symmetricDecryptBytes(encryptedBytes, base64Key);-- // Gzip magic number (0x1f 0x8b); anything else is treated as plain UTF-8.- if (decryptedBytes.length >= 2 && decryptedBytes[0] === 0x1f && decryptedBytes[1] === 0x8b) {- return strFromU8(gunzipSync(decryptedBytes));- }-- return Buffer.from(decryptedBytes).toString('utf8');- }-- /**- * Finds the decryption key of an email's symmetric key that one of the locally held keypairs can open. An email- * carries one decryption key per manifest keypair the caller holds; it names its public key by index into the- * publicKeys table the API sends once per response.- */- private static resolveEmailDecryptionKey(decryptionKeys: EmailDecryptionKey[], publicKeys: string[], encryptionKeys: EncryptionKey[]): { encryptionKey: EncryptionKey, encryptedSymmetricKey: string } {- for (const decryptionKey of decryptionKeys) {- const publicKey = publicKeys[decryptionKey.keyIndex];- const key = publicKey ? encryptionKeys.find(k => k.PublicKey === publicKey) : undefined;- if (key) {- return { encryptionKey: key, encryptedSymmetricKey: decryptionKey.encryptedSymmetricKey };- }- }-- throw new Error('Encryption key not found');- }-- /**- * Decrypts the symmetric key an email's contents are encrypted with, as base64.- */- private static async resolveEmailSymmetricKey(decryptionKeys: EmailDecryptionKey[], publicKeys: string[], encryptionKeys: EncryptionKey[]): Promise<string> {- const match = EncryptionUtility.resolveEmailDecryptionKey(decryptionKeys, publicKeys, encryptionKeys);- const symmetricKey = await rsaDecrypt(match.encryptedSymmetricKey, match.encryptionKey.PrivateKey);- return Buffer.from(symmetricKey).toString('base64');- }-- /**- * Decrypts an individual email based on the provided public/private key pairs and parses its source.- */- public static async decryptEmail(- email: Email,- encryptionKeys: EncryptionKey[]- ): Promise<DecryptedEmail> {- try {- const symmetricKeyBase64 = await EncryptionUtility.resolveEmailSymmetricKey(email.decryptionKeys, email.publicKeys, encryptionKeys);-- // Create a new object to avoid mutating the original- const decryptedEmail = { ...email };-- // Decrypt all email fields- decryptedEmail.subject = await EncryptionUtility.symmetricDecrypt(email.subject, symmetricKeyBase64);- decryptedEmail.fromDisplay = await EncryptionUtility.symmetricDecrypt(email.fromDisplay, symmetricKeyBase64);- decryptedEmail.fromDomain = await EncryptionUtility.symmetricDecrypt(email.fromDomain, symmetricKeyBase64);- decryptedEmail.fromLocal = await EncryptionUtility.symmetricDecrypt(email.fromLocal, symmetricKeyBase64);-- const sourceBytes = email.messageSource ? await EncryptionUtility.symmetricDecryptBytes(Uint8Array.from(atob(email.messageSource), c => c.charCodeAt(0)), symmetricKeyBase64) : null;- decryptedEmail.messageSource = '';-- let htmlBody: string | null = null;- let textBody: string | null = null;- let attachments: ParsedEmailAttachment[] = [];- if (sourceBytes) {- try {- const parsed = await parseEmailSource(sourceBytes);- htmlBody = parsed.htmlBody;- textBody = parsed.textBody;- attachments = parsed.attachments;- } catch (err) {- // A parse failure costs the bodies, not the email: the raw source view renders without the parser.- console.warn(`[Email] Could not parse the source of email ${email.id}:`, err);- }- }-- return { email: decryptedEmail, htmlBody, textBody, attachments, sourceBytes };- } catch (err) {- throw new Error(err instanceof Error ? err.message : 'Failed to decrypt email');- }- }-- /**- * Decrypts a list of emails based on the provided public/private key pairs. The publicKeys table is the one the- * API sent alongside the emails; each email's decryption keys reference it by index.- *- * Emails that cannot be decrypted are skipped rather than failing the batch, so one unreadable record cannot- * break the whole list view.- */- public static async decryptEmailList(- emails: MailboxEmail[],- publicKeys: string[],- encryptionKeys: EncryptionKey[]- ): Promise<MailboxEmail[]> {- const results = await Promise.all(emails.map(async email => {- try {- const symmetricKeyBase64 = await EncryptionUtility.resolveEmailSymmetricKey(email.decryptionKeys, publicKeys, encryptionKeys);-- // Create a new object to avoid mutating the original- const decryptedEmail = { ...email };-- // Decrypt all email fields- decryptedEmail.subject = await EncryptionUtility.symmetricDecrypt(email.subject, symmetricKeyBase64);- decryptedEmail.fromDisplay = await EncryptionUtility.symmetricDecrypt(email.fromDisplay, symmetricKeyBase64);- decryptedEmail.fromDomain = await EncryptionUtility.symmetricDecrypt(email.fromDomain, symmetricKeyBase64);- decryptedEmail.fromLocal = await EncryptionUtility.symmetricDecrypt(email.fromLocal, symmetricKeyBase64);-- if (email.messagePreview) {- decryptedEmail.messagePreview = await EncryptionUtility.symmetricDecrypt(email.messagePreview, symmetricKeyBase64);- }-- return decryptedEmail;- } catch (err) {- console.warn(`[Email] Skipping email ${email.id}, it could not be decrypted:`, err);- return null;- }- }));-- return results.filter((email): email is MailboxEmail => email !== null);- }-- /**- * Decrypts an attachment and returns the decrypted content as Uint8Array (raw bytes).- */- public static async decryptAttachment(- encryptedBytes: Uint8Array,- email: Email,- encryptionKeys: EncryptionKey[]- ): Promise<Uint8Array> {- try {- const symmetricKeyBase64 = await EncryptionUtility.resolveEmailSymmetricKey(email.decryptionKeys, email.publicKeys, encryptionKeys);-- // Decrypt the attachment using raw bytes- return await EncryptionUtility.symmetricDecryptBytes(encryptedBytes, symmetricKeyBase64);- } catch (err) {- throw new Error(err instanceof Error ? err.message : 'Failed to decrypt attachment');- }- }-}--export default EncryptionUtility;diff --git a/core/client/src/crypto/EncryptionUtility.ts b/core/client/src/crypto/EncryptionUtility.tsindex 27334ee93..3aa7453e0 100644--- a/core/client/src/crypto/EncryptionUtility.ts+++ b/core/client/src/crypto/EncryptionUtility.ts@@ -1,5 +1,5 @@import { devWarn } from '../platform/Logger';-import { argon2DeriveKey, parseEmailSource, type ParsedEmailAttachment } from '../rust/RustCore';+import { argon2DeriveKey, parseEmailSource, rustCore, type ParsedEmailAttachment } from '../rust/RustCore';import { base64ToBytes, bytesToBase64 } from '../utilities/Base64';import { logDefect } from '../utilities/Diagnostics';@@ -23,6 +23,14 @@ export type DecryptedEmail = {sourceBytes: Uint8Array | null;};+/**+ * Whether the host has WebCrypto. Hosts without it (the mobile app) run AES-GCM and the email key unwrap in the Rust+ * core, which writes the same `IV | ciphertext | tag` format; the web hosts keep WebCrypto for its speed on large blobs.+ */+function hasWebCrypto(): boolean {+ return typeof crypto !== 'undefined' && crypto.subtle !== undefined;+}+/*** Utility class for encryption operations including:* - Argon2Id key derivation@@ -56,6 +64,10 @@ export class EncryptionUtility {return plaintext;}+ if (!hasWebCrypto()) {+ return bytesToBase64(await rustCore().symmetricEncryptBytes(new TextEncoder().encode(plaintext), base64Key));+ }+const key = await crypto.subtle.importKey("raw",base64ToBytes(base64Key),@@ -88,6 +100,10 @@ export class EncryptionUtility {* Encrypts raw bytes using AES-GCM symmetric encryption.*/public static async symmetricEncryptBytes(plaintextBytes: Uint8Array, base64Key: string): Promise<string> {+ if (!hasWebCrypto()) {+ return bytesToBase64(await rustCore().symmetricEncryptBytes(plaintextBytes, base64Key));+ }+const key = await crypto.subtle.importKey("raw",base64ToBytes(base64Key),@@ -123,6 +139,10 @@ export class EncryptionUtility {return base64Ciphertext;}+ if (!hasWebCrypto()) {+ return rustCore().symmetricDecrypt(base64Ciphertext, base64Key);+ }+const key = await crypto.subtle.importKey("raw",base64ToBytes(base64Key),@@ -156,6 +176,10 @@ export class EncryptionUtility {return encryptedBytes;}+ if (!hasWebCrypto()) {+ return rustCore().symmetricDecryptBytes(encryptedBytes, base64Key);+ }+const key = await crypto.subtle.importKey("raw",base64ToBytes(base64Key),@@ -323,6 +347,10 @@ export class EncryptionUtility {*/private static async resolveEmailSymmetricKey(decryptionKeys: EmailDecryptionKey[], publicKeys: string[], encryptionKeys: EncryptionKey[]): Promise<string> {const match = EncryptionUtility.resolveEmailDecryptionKey(decryptionKeys, publicKeys, encryptionKeys);+ if (!hasWebCrypto()) {+ return bytesToBase64(await rustCore().rsaDecrypt(match.encryptedSymmetricKey, match.encryptionKey.PrivateKey));+ }+const privateKey = await EncryptionUtility.getPrivateKeyObject(match.encryptionKey);const symmetricKey = await EncryptionUtility.decryptWithPrivateKeyObject(match.encryptedSymmetricKey, privateKey);diff --git a/core/client/src/rust/RustCore.ts b/core/client/src/rust/RustCore.tsindex c50d5860e..733da454d 100644--- a/core/client/src/rust/RustCore.ts+++ b/core/client/src/rust/RustCore.ts@@ -12,12 +12,12 @@ import { deviceLanguage } from '../platform/DeviceLanguage';import { AutofillMatchingMode } from './RustCoreTypes';import type { IRustCore } from './RustCoreBinding';-import type { AccountKeyHierarchy, CodecCanonicalized, CodecCanonicalizeInput, FaviconTarget, IdentityNameInput, IdentityRequest, KeyChainOpenResult, ParsedEmail, ReencryptedAccountKey } from './RustCoreTypes';+import type { AccountKeyHierarchy, CodecCanonicalized, CodecCanonicalizeInput, FaviconTarget, IdentityNameInput, IdentityRequest, KeyChainOpenResult, ParsedEmail, PinFailure, ReencryptedAccountKey } from './RustCoreTypes';import type { Identity } from '@aliasvault/models/identity';import type { Item, PasswordSettings } from '@aliasvault/models/vault';export { AutofillMatchingMode } from './RustCoreTypes';-export type { CodecBlobEntry, CodecCanonicalized, CodecCanonicalizeInput, CodecDataBucket, CodecManifest, CodecTableData, FaviconTarget, IdentityNameInput, IdentityRequest, ParsedEmail, ParsedEmailAttachment } from './RustCoreTypes';+export type { CodecBlobEntry, CodecCanonicalized, CodecCanonicalizeInput, CodecDataBucket, CodecManifest, CodecTableData, FaviconTarget, IdentityNameInput, IdentityRequest, ParsedEmail, ParsedEmailAttachment, PinFailure } from './RustCoreTypes';/*** The host's Rust core binding.@@ -174,6 +174,41 @@ export async function extractEmailAttachment(source: Uint8Array, index: number,return rustCore().extractEmailAttachment(source, index, detachedBody);}+/**+ * A fresh random salt for a new PIN wrap.+ */+export async function pinGenerateSalt(): Promise<Uint8Array> {+ return rustCore().pinGenerateSalt();+}++/**+ * Encrypt `secret` with a key derived from the PIN and salt, as `IV | ciphertext | tag`.+ */+export async function pinEncrypt(pin: string, salt: Uint8Array, secret: Uint8Array): Promise<Uint8Array> {+ return rustCore().pinEncrypt(pin, salt, secret);+}++/**+ * Decrypt a PIN wrap. Rejects for a wrong PIN.+ */+export async function pinDecrypt(pin: string, salt: Uint8Array, encrypted: Uint8Array): Promise<Uint8Array> {+ return rustCore().pinDecrypt(pin, salt, encrypted);+}++/**+ * Whether a stored failed-attempt count means the PIN is locked.+ */+export async function pinIsLocked(failedAttempts: number): Promise<boolean> {+ return rustCore().pinIsLocked(failedAttempts);+}++/**+ * The counter state after one more failed PIN attempt on top of the stored count.+ */+export async function pinRegisterFailure(failedAttempts: number): Promise<PinFailure> {+ return rustCore().pinRegisterFailure(failedAttempts);+}+/*** Derive a 32-byte key from a password using Argon2id.*/diff --git a/core/client/src/rust/RustCoreBinding.ts b/core/client/src/rust/RustCoreBinding.tsindex a215418b5..8d77ca18d 100644--- a/core/client/src/rust/RustCoreBinding.ts+++ b/core/client/src/rust/RustCoreBinding.ts@@ -1,4 +1,4 @@-import type { AccountKeyHierarchy, CodecCanonicalized, CodecCanonicalizeInput, FaviconTarget, FilterCredentialsInput, FilterCredentialsOutput, KeyChainOpenResult, ParsedEmail, ReencryptedAccountKey, SrpEphemeral, SrpSession } from './RustCoreTypes';+import type { AccountKeyHierarchy, CodecCanonicalized, CodecCanonicalizeInput, FaviconTarget, FilterCredentialsInput, FilterCredentialsOutput, KeyChainOpenResult, ParsedEmail, PinFailure, ReencryptedAccountKey, SrpEphemeral, SrpSession } from './RustCoreTypes';/*** One running operation of the Rust vault sync engine.@@ -45,6 +45,17 @@ export interface IRustCore {decodeEmailSource(source: Uint8Array): Promise<Uint8Array>;extractEmailAttachment(source: Uint8Array, index: number, detachedBody?: Uint8Array): Promise<Uint8Array>;+ symmetricEncryptBytes(plaintext: Uint8Array, keyBase64: string): Promise<Uint8Array>;+ symmetricDecryptBytes(encrypted: Uint8Array, keyBase64: string): Promise<Uint8Array>;+ symmetricDecrypt(base64Ciphertext: string, keyBase64: string): Promise<string>;+ rsaDecrypt(base64Ciphertext: string, privateKeyJwk: string): Promise<Uint8Array>;++ pinGenerateSalt(): Promise<Uint8Array>;+ pinEncrypt(pin: string, salt: Uint8Array, secret: Uint8Array): Promise<Uint8Array>;+ pinDecrypt(pin: string, salt: Uint8Array, encrypted: Uint8Array): Promise<Uint8Array>;+ pinIsLocked(failedAttempts: number): Promise<boolean>;+ pinRegisterFailure(failedAttempts: number): Promise<PinFailure>;+argon2DeriveKey(password: string, salt: string, encryptionSettings: string): Promise<Uint8Array>;deriveSrpPasswordHash(unlockKeyBase64: string, encryptionType: string): Promise<string>;openAccountKeyChain(storedKey: string, encryptedAccountKey: string, encryptedVek: string, encryptedAccountPrivateKey: string | null): Promise<KeyChainOpenResult>;diff --git a/core/client/src/rust/RustCoreTypes.ts b/core/client/src/rust/RustCoreTypes.tsindex ecec7bbd5..02c3265ec 100644--- a/core/client/src/rust/RustCoreTypes.ts+++ b/core/client/src/rust/RustCoreTypes.ts@@ -80,6 +80,16 @@ export type SrpSession = {key: string;};+/** The PIN attempt counter after a failed attempt (the Rust `pin_register_failure`). */+export type PinFailure = {+ /** The failed-attempt count to store. */+ failedAttempts: number;+ /** Attempts left before the PIN locks; 0 when `locked`. */+ attemptsRemaining: number;+ /** Whether the host must now delete the PIN wrap and disable PIN unlock. */+ locked: boolean;+};+/*** The outcome of opening a key chain with a stored key (the Rust `open_account_key_chain`). Keys are base64; on* success `accountKey` is what the caller stores in place of the key it passed in.diff --git a/core/client/src/rust/WasmRustCore.ts b/core/client/src/rust/WasmRustCore.tsindex 84b02a82c..a8abdb51a 100644--- a/core/client/src/rust/WasmRustCore.ts+++ b/core/client/src/rust/WasmRustCore.ts@@ -6,7 +6,7 @@ import initWasm, * as core from '../../wasm/aliasvault_core.js';import { yieldToPaint } from '../utilities/YieldToPaint';import type { IRustCore, IVaultSyncSession } from './RustCoreBinding';-import type { AccountKeyHierarchy, CodecCanonicalized, CodecCanonicalizeInput, FaviconTarget, FilterCredentialsInput, FilterCredentialsOutput, KeyChainOpenResult, ParsedEmail, ReencryptedAccountKey, SrpEphemeral, SrpSession } from './RustCoreTypes';+import type { AccountKeyHierarchy, CodecCanonicalized, CodecCanonicalizeInput, FaviconTarget, FilterCredentialsInput, FilterCredentialsOutput, KeyChainOpenResult, ParsedEmail, PinFailure, ReencryptedAccountKey, SrpEphemeral, SrpSession } from './RustCoreTypes';/*** Where the host gets the `.wasm` binary from: bytes, or a fetch response for streaming instantiation.@@ -69,10 +69,27 @@ export function createWasmRustCore(loadWasm: WasmLoader): IRustCore {decodeEmailSource: (source): Promise<Uint8Array> => ready(() => core.decodeEmailSource(source)),extractEmailAttachment: (source, index, detachedBody): Promise<Uint8Array> => ready(() => core.extractEmailAttachment(source, index, detachedBody)),+ symmetricEncryptBytes: (plaintext, keyBase64): Promise<Uint8Array> => ready(() => core.symmetricEncryptBytes(plaintext, keyBase64)),+ symmetricDecryptBytes: (encrypted, keyBase64): Promise<Uint8Array> => ready(() => core.symmetricDecryptBytes(encrypted, keyBase64)),+ symmetricDecrypt: (base64Ciphertext, keyBase64): Promise<string> => ready(() => core.symmetricDecrypt(base64Ciphertext, keyBase64)),+ rsaDecrypt: (base64Ciphertext, privateKeyJwk): Promise<Uint8Array> => ready(() => core.rsaDecrypt(base64Ciphertext, privateKeyJwk)),+/*- * Argon2 blocks the thread it runs on for up to a few seconds on slow devices, so let the caller's loading- * indicator paint first before proceeding with the expensive operation.+ * Argon2 (also behind pinEncrypt and pinDecrypt) blocks the thread it runs on for up to a few seconds on slow+ * devices, so let the caller's loading indicator paint first before proceeding with the expensive operation.*/+ pinGenerateSalt: (): Promise<Uint8Array> => ready(() => core.pinGenerateSalt()),+ pinEncrypt: async (pin, salt, secret): Promise<Uint8Array> => {+ await yieldToPaint();+ return ready(() => core.pinEncrypt(pin, salt, secret));+ },+ pinDecrypt: async (pin, salt, encrypted): Promise<Uint8Array> => {+ await yieldToPaint();+ return ready(() => core.pinDecrypt(pin, salt, encrypted));+ },+ pinIsLocked: (failedAttempts): Promise<boolean> => ready(() => core.pinIsLocked(failedAttempts)),+ pinRegisterFailure: (failedAttempts): Promise<PinFailure> => ready(() => core.pinRegisterFailure(failedAttempts) as PinFailure),+argon2DeriveKey: async (password, salt, encryptionSettings): Promise<Uint8Array> => {await yieldToPaint();return ready(() => core.argon2DeriveKey(password, salt, encryptionSettings));diff --git a/core/rust/src/bindings/uniffi_api.rs b/core/rust/src/bindings/uniffi_api.rsindex e6ecc492b..1c8818c65 100644--- a/core/rust/src/bindings/uniffi_api.rs+++ b/core/rust/src/bindings/uniffi_api.rs@@ -186,10 +186,52 @@ pub fn argon2_derive_key(password: String, salt: String, encryption_settings: Stcrate::crypto::argon2::argon2_derive_key_from_settings(&password, &salt, &encryption_settings)}-/// `argon2_derive_key` over raw bytes: the mobile PIN unlock's Keychain/Keystore salt is random bytes, not UTF-8.+/// AES-256-GCM encrypt bytes with a base64 key. Returns `IV | ciphertext | tag`.#[uniffi::export]-pub fn argon2_derive_key_bytes(password: Vec<u8>, salt: Vec<u8>, encryption_settings: String) -> Result<Vec<u8>, Argon2Error> {- crate::crypto::argon2::argon2_derive_key_bytes_from_settings(&password, &salt, &encryption_settings)+pub fn symmetric_encrypt_bytes(plaintext: Vec<u8>, key_base64: String) -> Result<Vec<u8>, VaultError> {+ crate::crypto::symmetric_encrypt_raw_with_aad(&plaintext, &key_base64, &[])+}++/// AES-256-GCM decrypt `IV | ciphertext | tag` bytes with a base64 key.+#[uniffi::export]+pub fn symmetric_decrypt_bytes(encrypted: Vec<u8>, key_base64: String) -> Result<Vec<u8>, VaultError> {+ crate::crypto::symmetric_decrypt_bytes(&encrypted, &key_base64)+}++/// AES-256-GCM decrypt a base64 `IV | ciphertext | tag` string into UTF-8 with a base64 key; empty stays empty.+#[uniffi::export]+pub fn symmetric_decrypt(base64_ciphertext: String, key_base64: String) -> Result<String, VaultError> {+ crate::crypto::symmetric_decrypt(&base64_ciphertext, &key_base64)+}++/// A fresh random salt for a new PIN wrap.+#[uniffi::export]+pub fn pin_generate_salt() -> Vec<u8> {+ crate::crypto::pin_generate_salt()+}++/// Encrypt `secret` with a key derived from the PIN and salt. Returns `IV | ciphertext | tag`.+#[uniffi::export]+pub fn pin_encrypt(pin: String, salt: Vec<u8>, secret: Vec<u8>) -> Result<Vec<u8>, VaultError> {+ crate::crypto::pin_encrypt(&pin, &salt, &secret)+}++/// Decrypt a PIN wrap. Fails for a wrong PIN.+#[uniffi::export]+pub fn pin_decrypt(pin: String, salt: Vec<u8>, encrypted: Vec<u8>) -> Result<Vec<u8>, VaultError> {+ crate::crypto::pin_decrypt(&pin, &salt, &encrypted)+}++/// Whether a stored failed-attempt count means the PIN is locked.+#[uniffi::export]+pub fn pin_is_locked(failed_attempts: u32) -> bool {+ crate::crypto::pin_is_locked(failed_attempts)+}++/// The counter state after one more failed PIN attempt on top of the stored count.+#[uniffi::export]+pub fn pin_register_failure(failed_attempts: u32) -> crate::crypto::PinFailure {+ crate::crypto::pin_register_failure(failed_attempts)}/// Create a new account key hierarchy for the unlock key around an account keypair (JWK) the caller generated, as JSON.diff --git a/core/rust/src/bindings/wasm.rs b/core/rust/src/bindings/wasm.rsindex e18abfdf7..cf67e7392 100644--- a/core/rust/src/bindings/wasm.rs+++ b/core/rust/src/bindings/wasm.rs@@ -198,6 +198,60 @@ pub fn argon2_derive_key_js(password: &str, salt: &str, encryption_settings: &stcrate::crypto::argon2::argon2_derive_key_from_settings(password, salt, encryption_settings).map_err(js_err)}+/// AES-256-GCM encrypt bytes with a base64 key. Returns `IV | ciphertext | tag`.+#[wasm_bindgen(js_name = symmetricEncryptBytes)]+pub fn symmetric_encrypt_bytes_js(plaintext: &[u8], key_base64: &str) -> Result<Vec<u8>, JsValue> {+ crate::crypto::symmetric_encrypt_raw_with_aad(plaintext, key_base64, &[]).map_err(js_err)+}++/// AES-256-GCM decrypt `IV | ciphertext | tag` bytes with a base64 key.+#[wasm_bindgen(js_name = symmetricDecryptBytes)]+pub fn symmetric_decrypt_bytes_js(encrypted: &[u8], key_base64: &str) -> Result<Vec<u8>, JsValue> {+ crate::crypto::symmetric_decrypt_bytes(encrypted, key_base64).map_err(js_err)+}++/// AES-256-GCM decrypt a base64 `IV | ciphertext | tag` string into UTF-8 with a base64 key; empty stays empty.+#[wasm_bindgen(js_name = symmetricDecrypt)]+pub fn symmetric_decrypt_js(base64_ciphertext: &str, key_base64: &str) -> Result<String, JsValue> {+ crate::crypto::symmetric_decrypt(base64_ciphertext, key_base64).map_err(js_err)+}++/// RSA-OAEP-256 decrypt base64 ciphertext with a JWK private key.+#[wasm_bindgen(js_name = rsaDecrypt)]+pub fn rsa_decrypt_js(base64_ciphertext: &str, private_key_jwk: &str) -> Result<Vec<u8>, JsValue> {+ crate::crypto::decrypt_with_private_key(base64_ciphertext, private_key_jwk).map_err(js_err)+}++/// A fresh random salt for a new PIN wrap.+#[wasm_bindgen(js_name = pinGenerateSalt)]+pub fn pin_generate_salt_js() -> Vec<u8> {+ crate::crypto::pin_generate_salt()+}++/// Encrypt `secret` with a key derived from the PIN and salt. Returns `IV | ciphertext | tag`.+#[wasm_bindgen(js_name = pinEncrypt)]+pub fn pin_encrypt_js(pin: &str, salt: &[u8], secret: &[u8]) -> Result<Vec<u8>, JsValue> {+ crate::crypto::pin_encrypt(pin, salt, secret).map_err(js_err)+}++/// Decrypt a PIN wrap. Fails for a wrong PIN.+#[wasm_bindgen(js_name = pinDecrypt)]+pub fn pin_decrypt_js(pin: &str, salt: &[u8], encrypted: &[u8]) -> Result<Vec<u8>, JsValue> {+ crate::crypto::pin_decrypt(pin, salt, encrypted).map_err(js_err)+}++/// Whether a stored failed-attempt count means the PIN is locked.+#[wasm_bindgen(js_name = pinIsLocked)]+pub fn pin_is_locked_js(failed_attempts: u32) -> bool {+ crate::crypto::pin_is_locked(failed_attempts)+}++/// The counter state after one more failed PIN attempt on top of the stored count.+#[wasm_bindgen(js_name = pinRegisterFailure)]+pub fn pin_register_failure_js(failed_attempts: u32) -> Result<JsValue, JsValue> {+ to_js(&crate::crypto::pin_register_failure(failed_attempts))+}+/// Create a new account key hierarchy for the base64 unlock key around an account keypair (JWK) the caller generated.#[wasm_bindgen(js_name = createAccountKeyHierarchy)]pub fn create_account_key_hierarchy_js(unlock_key_base64: &str, public_key_jwk: String, private_key_jwk: String) -> Result<JsValue, JsValue> {diff --git a/core/rust/src/crypto/aes_gcm.rs b/core/rust/src/crypto/aes_gcm.rsindex 8b0b682c8..6541f99ca 100644--- a/core/rust/src/crypto/aes_gcm.rs+++ b/core/rust/src/crypto/aes_gcm.rs@@ -31,7 +31,20 @@ pub fn symmetric_encrypt_bytes_with_aad(plaintext: &[u8], key_base64: &str, aad:/// Encrypt bytes bound to `aad`, which decryption must present as-is. Returns the raw `IV | ciphertext | tag`.pub fn symmetric_encrypt_raw_with_aad(plaintext: &[u8], key_base64: &str, aad: &[u8]) -> VaultResult<Vec<u8>> {- let cipher = cipher_for(key_base64)?;+ encrypt_with_cipher(&cipher_for(key_base64)?, plaintext, aad)+}++/// Encrypt bytes with a raw 32-byte key and no associated data. Returns the raw `IV | ciphertext | tag`.+pub fn symmetric_encrypt_with_raw_key(plaintext: &[u8], key: &[u8]) -> VaultResult<Vec<u8>> {+ encrypt_with_cipher(&cipher_from_bytes(key)?, plaintext, &[])+}++/// Decrypt raw `IV | ciphertext | tag` bytes with a raw 32-byte key and no associated data.+pub fn symmetric_decrypt_with_raw_key(iv_and_ciphertext: &[u8], key: &[u8]) -> VaultResult<Vec<u8>> {+ decrypt_with_cipher(&cipher_from_bytes(key)?, iv_and_ciphertext, &[])+}++fn encrypt_with_cipher(cipher: &Aes256Gcm, plaintext: &[u8], aad: &[u8]) -> VaultResult<Vec<u8>> {let mut iv = [0u8; IV_LENGTH];fill_random(&mut iv);@@ -52,10 +65,13 @@ pub fn symmetric_decrypt_bytes(iv_and_ciphertext: &[u8], key_base64: &str) -> Va/// Decrypt `IV | ciphertext | tag` bytes that were encrypted bound to `aad`.pub fn symmetric_decrypt_bytes_with_aad(iv_and_ciphertext: &[u8], key_base64: &str, aad: &[u8]) -> VaultResult<Vec<u8>> {+ decrypt_with_cipher(&cipher_for(key_base64)?, iv_and_ciphertext, aad)+}++fn decrypt_with_cipher(cipher: &Aes256Gcm, iv_and_ciphertext: &[u8], aad: &[u8]) -> VaultResult<Vec<u8>> {if iv_and_ciphertext.len() < IV_LENGTH {return Err(VaultError::General("AES-GCM ciphertext is too short".to_string()));}- let cipher = cipher_for(key_base64)?;let (iv, ciphertext) = iv_and_ciphertext.split_at(IV_LENGTH);cipher.decrypt(Nonce::from_slice(iv), Payload { msg: ciphertext, aad })@@ -97,11 +113,14 @@ pub fn symmetric_decrypt_with_aad(base64_ciphertext: &str, key_base64: &str, aad}fn cipher_for(key_base64: &str) -> VaultResult<Aes256Gcm> {- let key = Zeroizing::new(base64_decode(key_base64)?);+ cipher_from_bytes(&Zeroizing::new(base64_decode(key_base64)?))+}++fn cipher_from_bytes(key: &[u8]) -> VaultResult<Aes256Gcm> {if key.len() != KEY_LENGTH {return Err(VaultError::General(format!("AES-GCM key must be {} bytes, got {}", KEY_LENGTH, key.len())));}- Ok(Aes256Gcm::new_from_slice(&key[..]).expect("key length checked above"))+ Ok(Aes256Gcm::new_from_slice(key).expect("key length checked above"))}#[cfg(test)]diff --git a/core/rust/src/crypto/mod.rs b/core/rust/src/crypto/mod.rsindex edf0eeca7..4cb7fa1fb 100644--- a/core/rust/src/crypto/mod.rs+++ b/core/rust/src/crypto/mod.rs@@ -4,6 +4,7 @@ pub mod aad;pub mod aes_gcm;pub mod argon2;pub mod key_chain;+pub mod pin;pub mod rsa_oaep;pub mod signing;pub mod srp;@@ -12,6 +13,7 @@ pub use aes_gcm::{generate_key_base64, symmetric_decrypt, symmetric_decrypt_bytes, symmetric_decrypt_bytes_with_aad, symmetric_decrypt_with_aad, symmetric_encrypt, symmetric_encrypt_bytes, symmetric_encrypt_bytes_with_aad,symmetric_encrypt_raw_with_aad, symmetric_encrypt_with_aad,};+pub use pin::{pin_decrypt, pin_encrypt, pin_generate_salt, pin_is_locked, pin_register_failure, PinFailure, PIN_MAX_ATTEMPTS};pub use key_chain::{create_account_key_hierarchy, create_account_key_hierarchy_with_key_pair, derive_kek, derive_kek_base64, derive_srp_password_hash, open_account_key_chain, open_account_private_key, open_account_signing_private_key, reencrypt_account_key, unwrap_account_key, unwrap_key, wrap_account_key, wrap_key, AccountKeyBlobs,AccountKeyHierarchy, KeyChainError, OpenedKeyChain, ReencryptedAccountKey, SrpInputError, ENCRYPTION_TYPE_ARGON2ID, ENCRYPTION_TYPE_ARGON2ID_HKDF,diff --git a/core/rust/src/crypto/pin.rs b/core/rust/src/crypto/pin.rsnew file mode 100644index 000000000..a4cb3055b--- /dev/null+++ b/core/rust/src/crypto/pin.rs@@ -0,0 +1,99 @@+//! PIN unlock: the key wrap and the failed-attempt policy.++use serde::Serialize;+use zeroize::Zeroizing;++use crate::common::error::{VaultError, VaultResult};+use crate::common::rng::fill_random;+use crate::crypto::aes_gcm::{symmetric_decrypt_with_raw_key, symmetric_encrypt_with_raw_key};+use crate::crypto::argon2::argon2_derive_key_bytes_from_settings;++/// Failed attempts after which the PIN is locked and the host deletes the wrapped key.+pub const PIN_MAX_ATTEMPTS: u32 = 4;++/// Length of the random salt a new PIN wrap is derived with.+const PIN_SALT_LENGTH: usize = 16;++/// Argon2id cost parameters for the PIN key. Note: changing this makes any existing PINs not work anymore.+const PIN_ARGON2_SETTINGS: &str = r#"{"MemorySize":65536,"Iterations":3,"DegreeOfParallelism":1}"#;++/// The counter state after a failed PIN attempt.+#[derive(Clone, Debug, PartialEq, Eq, Serialize)]+#[serde(rename_all = "camelCase")]+#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]+pub struct PinFailure {+ /// The failed-attempt count to store.+ pub failed_attempts: u32,+ /// Attempts left before the PIN locks; 0 when `locked`.+ pub attempts_remaining: u32,+ /// Whether the host must now delete the wrapped key and disable PIN unlock.+ pub locked: bool,+}++/// A fresh random salt for a new PIN wrap.+pub fn pin_generate_salt() -> Vec<u8> {+ let mut salt = vec![0u8; PIN_SALT_LENGTH];+ fill_random(&mut salt);+ salt+}++/// Encrypt `secret` with a key derived from the PIN and salt. Returns `IV | ciphertext | tag`.+pub fn pin_encrypt(pin: &str, salt: &[u8], secret: &[u8]) -> VaultResult<Vec<u8>> {+ symmetric_encrypt_with_raw_key(secret, &derive_pin_key(pin, salt)?)+}++/// Decrypt a PIN wrap made by [`pin_encrypt`]. Fails for a wrong PIN.+pub fn pin_decrypt(pin: &str, salt: &[u8], encrypted: &[u8]) -> VaultResult<Vec<u8>> {+ symmetric_decrypt_with_raw_key(encrypted, &derive_pin_key(pin, salt)?)+}++/// Whether a stored failed-attempt count means the PIN is locked.+pub fn pin_is_locked(failed_attempts: u32) -> bool {+ failed_attempts >= PIN_MAX_ATTEMPTS+}++/// The counter state after one more failed attempt on top of the stored count.+pub fn pin_register_failure(failed_attempts: u32) -> PinFailure {+ let failed_attempts = failed_attempts.saturating_add(1);+ PinFailure { failed_attempts, attempts_remaining: PIN_MAX_ATTEMPTS.saturating_sub(failed_attempts), locked: pin_is_locked(failed_attempts) }+}++fn derive_pin_key(pin: &str, salt: &[u8]) -> VaultResult<Zeroizing<Vec<u8>>> {+ argon2_derive_key_bytes_from_settings(pin.as_bytes(), salt, PIN_ARGON2_SETTINGS).map(Zeroizing::new).map_err(|e| VaultError::General(e.to_string()))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn round_trips_and_rejects_a_wrong_pin() {+ let salt = pin_generate_salt();+ assert_eq!(salt.len(), PIN_SALT_LENGTH);+ let encrypted = pin_encrypt("123456", &salt, b"account key").unwrap();+ assert_eq!(encrypted.len(), 12 + b"account key".len() + 16, "layout is IV | ciphertext | tag");+ assert_eq!(pin_decrypt("123456", &salt, &encrypted).unwrap(), b"account key");+ assert!(pin_decrypt("654321", &salt, &encrypted).is_err());+ assert!(pin_decrypt("123456", &pin_generate_salt(), &encrypted).is_err());+ }++ #[test]+ fn opens_a_wrap_made_with_the_argon2_key_directly() {+ // A wrap stored before this module existed: Argon2id under the PIN settings, then AES-GCM with that key.+ let salt = b"some-salt-bytes!";+ let key = argon2_derive_key_bytes_from_settings(b"8765432", salt, PIN_ARGON2_SETTINGS).unwrap();+ let encrypted = symmetric_encrypt_with_raw_key(b"secret", &key).unwrap();+ assert_eq!(pin_decrypt("8765432", salt, &encrypted).unwrap(), b"secret");+ }++ #[test]+ fn locks_after_the_maximum_attempts() {+ assert!(!pin_is_locked(0));+ assert!(!pin_is_locked(PIN_MAX_ATTEMPTS - 1));+ assert!(pin_is_locked(PIN_MAX_ATTEMPTS));+ assert_eq!(pin_register_failure(0), PinFailure { failed_attempts: 1, attempts_remaining: 3, locked: false });+ assert_eq!(pin_register_failure(2), PinFailure { failed_attempts: 3, attempts_remaining: 1, locked: false });+ assert_eq!(pin_register_failure(3), PinFailure { failed_attempts: 4, attempts_remaining: 0, locked: true });+ assert_eq!(pin_register_failure(u32::MAX), PinFailure { failed_attempts: u32::MAX, attempts_remaining: 0, locked: true });+ }+}