Skip to content

Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.

feat: cache email RSA CryptoKeys by public key

AmarBego4a42b5363c4b
diff --git a/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsx b/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsx
index 562a7803f..014906f1e 100644
--- a/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsx
@@ -1,6 +1,7 @@
import React, { createContext, useContext, useState, useEffect, useCallback, useMemo, useRef } from 'react';
import type { EncryptionKeyDerivationParams } from '@/utils/dist/core/models/metadata';
+import EncryptionUtility from '@/utils/EncryptionUtility';
import { sendMessage } from '@/utils/messaging/ExtensionMessaging';
import SqliteClient from '@/utils/SqliteClient';
import { getItemWithFallback } from '@/utils/StorageUtility';
@@ -217,6 +218,7 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }
// Reflect locks from other windows.
useEffect(() => {
return vaultStateEvents.onVaultLocked(() => {
+ EncryptionUtility.clearRsaPrivateKeyCache();
setSqliteClient(null);
setDbAvailable(false);
});
@@ -379,6 +381,7 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }
* Clear database and remove from background worker, called when logging out.
*/
const clearDatabase = useCallback(() : void => {
+ EncryptionUtility.clearRsaPrivateKeyCache();
setSqliteClient(null);
setDbInitialized(false);
setDbAvailable(false);
diff --git a/apps/browser-extension/src/utils/EncryptionUtility.ts b/apps/browser-extension/src/utils/EncryptionUtility.ts
index acfac8cb5..0a7647796 100644
--- a/apps/browser-extension/src/utils/EncryptionUtility.ts
+++ b/apps/browser-extension/src/utils/EncryptionUtility.ts
@@ -12,6 +12,8 @@ import type { Email, MailboxEmail } from '@/utils/dist/core/models/webapi';
* - RSA-OAEP asymmetric encryption/decryption
*/
export class EncryptionUtility {
+ private static rsaPrivateKeyCache = new Map<string, Promise<CryptoKey>>();
+
/**
* Derives a key from a password using Argon2Id
*/
@@ -230,16 +232,7 @@ export class EncryptionUtility {
*/
public static async decryptWithPrivateKey(ciphertext: string, privateKey: string): Promise<Uint8Array> {
try {
- const privateKeyObj = await crypto.subtle.importKey(
- "jwk",
- JSON.parse(privateKey),
- {
- name: "RSA-OAEP",
- hash: "SHA-256",
- },
- false,
- ["decrypt"]
- );
+ const privateKeyObj = await EncryptionUtility.importPrivateKey(privateKey);
return await EncryptionUtility.decryptWithPrivateKeyObject(ciphertext, privateKeyObj);
} catch (error) {
@@ -264,6 +257,48 @@ export class EncryptionUtility {
return new Uint8Array(plaintextBuffer);
}
+ /**
+ * Clears cached RSA private keys when the in-memory vault is locked or reset.
+ */
+ public static clearRsaPrivateKeyCache(): void {
+ EncryptionUtility.rsaPrivateKeyCache.clear();
+ }
+
+ /**
+ * Imports an RSA-OAEP private key as non-extractable.
+ */
+ private static async importPrivateKey(privateKey: string): Promise<CryptoKey> {
+ return await crypto.subtle.importKey(
+ "jwk",
+ JSON.parse(privateKey),
+ {
+ name: "RSA-OAEP",
+ hash: "SHA-256",
+ },
+ false,
+ ["decrypt"]
+ );
+ }
+
+ /**
+ * Returns the cached non-extractable private key matching an email encryption public key.
+ */
+ private static async getPrivateKeyObject(encryptionKey: EncryptionKey): Promise<CryptoKey> {
+ const cachedPrivateKey = EncryptionUtility.rsaPrivateKeyCache.get(encryptionKey.PublicKey);
+
+ if (cachedPrivateKey) {
+ return await cachedPrivateKey;
+ }
+
+ const privateKey = EncryptionUtility.importPrivateKey(encryptionKey.PrivateKey).catch(error => {
+ EncryptionUtility.rsaPrivateKeyCache.delete(encryptionKey.PublicKey);
+ throw error;
+ });
+
+ EncryptionUtility.rsaPrivateKeyCache.set(encryptionKey.PublicKey, privateKey);
+ return await privateKey;
+ }
+
/**
* Decrypts an individual email based on the provided public/private key pairs.
*/
@@ -279,9 +314,10 @@ export class EncryptionUtility {
}
// Decrypt symmetric key with asymmetric private key
- const symmetricKey = await EncryptionUtility.decryptWithPrivateKey(
+ const privateKey = await EncryptionUtility.getPrivateKeyObject(encryptionKey);
+ const symmetricKey = await EncryptionUtility.decryptWithPrivateKeyObject(
email.encryptedSymmetricKey,
- encryptionKey.PrivateKey
+ privateKey
);
const symmetricKeyBase64 = Buffer.from(symmetricKey).toString('base64');
@@ -323,9 +359,10 @@ export class EncryptionUtility {
}
// Decrypt symmetric key with asymmetric private key
- const symmetricKey = await EncryptionUtility.decryptWithPrivateKey(
+ const privateKey = await EncryptionUtility.getPrivateKeyObject(encryptionKey);
+ const symmetricKey = await EncryptionUtility.decryptWithPrivateKeyObject(
email.encryptedSymmetricKey,
- encryptionKey.PrivateKey
+ privateKey
);
const symmetricKeyBase64 = Buffer.from(symmetricKey).toString('base64');
@@ -365,9 +402,10 @@ export class EncryptionUtility {
}
// Decrypt the symmetric key using private key (returns raw bytes)
- const symmetricKey = await EncryptionUtility.decryptWithPrivateKey(
+ const privateKey = await EncryptionUtility.getPrivateKeyObject(encryptionKey);
+ const symmetricKey = await EncryptionUtility.decryptWithPrivateKeyObject(
email.encryptedSymmetricKey,
- encryptionKey.PrivateKey
+ privateKey
);
// Convert symmetric key to base64 string if symmetricDecrypt expects it
diff --git a/apps/browser-extension/src/utils/__tests__/EncryptionUtility.crypto.test.ts b/apps/browser-extension/src/utils/__tests__/EncryptionUtility.crypto.test.ts
index 719acb264..9ae486918 100644
--- a/apps/browser-extension/src/utils/__tests__/EncryptionUtility.crypto.test.ts
+++ b/apps/browser-extension/src/utils/__tests__/EncryptionUtility.crypto.test.ts
@@ -1,7 +1,102 @@
-import { describe, it, expect } from 'vitest';
+import { beforeEach, describe, it, expect, vi } from 'vitest';
+import type { EncryptionKey } from '@/utils/dist/core/models/vault';
+import type { Email, MailboxEmail } from '@/utils/dist/core/models/webapi';
import EncryptionUtility from '@/utils/EncryptionUtility';
+beforeEach(() => {
+ EncryptionUtility.clearRsaPrivateKeyCache();
+});
+
+/**
+ * Creates a mailbox email with fields encrypted by the supplied RSA key pair.
+ */
+async function createMailboxEmail(
+ id: number,
+ encryptionKey: EncryptionKey,
+ rawSymmetricKey: string,
+ subject: string
+): Promise<MailboxEmail> {
+ const symmetricKeyBase64 = Buffer.from(rawSymmetricKey).toString('base64');
+
+ return {
+ messagePreview: await EncryptionUtility.symmetricEncrypt(`Preview ${id}`, symmetricKeyBase64),
+ hasAttachments: false,
+ id,
+ subject: await EncryptionUtility.symmetricEncrypt(subject, symmetricKeyBase64),
+ fromDisplay: await EncryptionUtility.symmetricEncrypt(`Sender ${id}`, symmetricKeyBase64),
+ fromDomain: await EncryptionUtility.symmetricEncrypt('example.com', symmetricKeyBase64),
+ fromLocal: await EncryptionUtility.symmetricEncrypt(`sender${id}`, symmetricKeyBase64),
+ toDomain: 'aliasvault.net',
+ toLocal: `alias${id}`,
+ date: '2026-05-26T00:00:00Z',
+ dateSystem: '2026-05-26T00:00:00Z',
+ secondsAgo: id,
+ encryptedSymmetricKey: await EncryptionUtility.encryptWithPublicKey(rawSymmetricKey, encryptionKey.PublicKey),
+ encryptionKey: encryptionKey.PublicKey,
+ };
+}
+
+/**
+ * Creates an email with the supplied symmetric key encrypted by the RSA key pair.
+ */
+async function createEmail(
+ encryptionKey: EncryptionKey,
+ rawSymmetricKey: string
+): Promise<Email> {
+ return {
+ messageHtml: '',
+ messagePlain: '',
+ id: 1,
+ subject: '',
+ fromDisplay: '',
+ fromDomain: '',
+ fromLocal: '',
+ toDomain: 'aliasvault.net',
+ toLocal: 'alias',
+ date: '2026-05-26T00:00:00Z',
+ dateSystem: '2026-05-26T00:00:00Z',
+ secondsAgo: 1,
+ encryptedSymmetricKey: await EncryptionUtility.encryptWithPublicKey(rawSymmetricKey, encryptionKey.PublicKey),
+ encryptionKey: encryptionKey.PublicKey,
+ attachments: [],
+ };
+}
+
+/**
+ * Encrypts bytes in the same IV+ciphertext format used by attachment decryption.
+ */
+async function encryptAttachmentBytes(plaintext: Uint8Array, rawSymmetricKey: string): Promise<Uint8Array> {
+ const key = await crypto.subtle.importKey(
+ 'raw',
+ Uint8Array.from(rawSymmetricKey, c => c.charCodeAt(0)),
+ {
+ name: 'AES-GCM',
+ length: 256,
+ },
+ false,
+ ['encrypt']
+ );
+ const iv = crypto.getRandomValues(new Uint8Array(12));
+ const ciphertext = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, key, plaintext);
+ const encryptedBytes = new Uint8Array(iv.length + ciphertext.byteLength);
+ encryptedBytes.set(iv, 0);
+ encryptedBytes.set(new Uint8Array(ciphertext), iv.length);
+ return encryptedBytes;
+}
+
+/**
+ * Counts non-extractable RSA private-key imports.
+ */
+function countPrivateKeyImports(importKeyCalls: unknown[][]): number {
+ return importKeyCalls.filter(call =>
+ call[0] === 'jwk' &&
+ call[3] === false &&
+ Array.isArray(call[4]) &&
+ call[4].includes('decrypt')
+ ).length;
+}
+
describe('generateRsaKeyPairNonExtractable', () => {
it('returns a non-extractable CryptoKey for the private half', async () => {
const { privateKey } = await EncryptionUtility.generateRsaKeyPairNonExtractable();
@@ -59,3 +154,72 @@ describe('generateRsaKeyPair (legacy JWK path, used by vault email decrypt)', ()
expect(jwk.q).toBeDefined();
});
});
+
+describe('email RSA private key cache', () => {
+ it('caches multiple non-extractable private keys by matching public key', async () => {
+ const keyPairA = await EncryptionUtility.generateRsaKeyPair();
+ const keyPairB = await EncryptionUtility.generateRsaKeyPair();
+ const encryptionKeyA: EncryptionKey = {
+ Id: 'key-a',
+ PublicKey: keyPairA.publicKey,
+ PrivateKey: keyPairA.privateKey,
+ IsPrimary: true,
+ };
+ const encryptionKeyB: EncryptionKey = {
+ Id: 'key-b',
+ PublicKey: keyPairB.publicKey,
+ PrivateKey: keyPairB.privateKey,
+ IsPrimary: false,
+ };
+ const emails = [
+ await createMailboxEmail(1, encryptionKeyA, '0123456789abcdef0123456789abcdef', 'Subject A1'),
+ await createMailboxEmail(2, encryptionKeyA, 'abcdef0123456789abcdef0123456789', 'Subject A2'),
+ await createMailboxEmail(3, encryptionKeyB, 'fedcba9876543210fedcba9876543210', 'Subject B1'),
+ ];
+ const importKeySpy = vi.spyOn(crypto.subtle, 'importKey');
+
+ try {
+ const decryptedEmails = await EncryptionUtility.decryptEmailList(emails, [encryptionKeyA, encryptionKeyB]);
+
+ expect(decryptedEmails.map(email => email.subject)).toEqual(['Subject A1', 'Subject A2', 'Subject B1']);
+ expect(countPrivateKeyImports(importKeySpy.mock.calls as unknown[][])).toBe(2);
+
+ await EncryptionUtility.decryptEmailList([emails[0]], [encryptionKeyA, encryptionKeyB]);
+ expect(countPrivateKeyImports(importKeySpy.mock.calls as unknown[][])).toBe(2);
+
+ EncryptionUtility.clearRsaPrivateKeyCache();
+ await EncryptionUtility.decryptEmailList([emails[0]], [encryptionKeyA, encryptionKeyB]);
+ expect(countPrivateKeyImports(importKeySpy.mock.calls as unknown[][])).toBe(3);
+ } finally {
+ importKeySpy.mockRestore();
+ }
+ });
+
+ it('reuses cached private keys when decrypting attachments', async () => {
+ const keyPair = await EncryptionUtility.generateRsaKeyPair();
+ const encryptionKey: EncryptionKey = {
+ Id: 'key-a',
+ PublicKey: keyPair.publicKey,
+ PrivateKey: keyPair.privateKey,
+ IsPrimary: true,
+ };
+ const rawSymmetricKey = '0123456789abcdef0123456789abcdef';
+ const email = await createEmail(encryptionKey, rawSymmetricKey);
+ const encryptedBytes = await encryptAttachmentBytes(
+ new TextEncoder().encode('attachment body'),
+ rawSymmetricKey
+ );
+ const importKeySpy = vi.spyOn(crypto.subtle, 'importKey');
+
+ try {
+ const decryptedBytes = await EncryptionUtility.decryptAttachment(encryptedBytes, email, [encryptionKey]);
+ expect(new TextDecoder().decode(decryptedBytes)).toBe('attachment body');
+ expect(countPrivateKeyImports(importKeySpy.mock.calls as unknown[][])).toBe(1);
+
+ await EncryptionUtility.decryptAttachment(encryptedBytes, email, [encryptionKey]);
+ expect(countPrivateKeyImports(importKeySpy.mock.calls as unknown[][])).toBe(1);
+ } finally {
+ importKeySpy.mockRestore();
+ }
+ });
+});
diff --git a/apps/mobile-app/context/AuthContext.tsx b/apps/mobile-app/context/AuthContext.tsx
index d5b1c11bd..b10cbda5c 100644
--- a/apps/mobile-app/context/AuthContext.tsx
+++ b/apps/mobile-app/context/AuthContext.tsx
@@ -163,6 +163,7 @@ export const AuthProvider: React.FC<{
// Clear auth tokens and session in native layer (preserves vault data)
await NativeVaultManager.clearAuthTokens();
await NativeVaultManager.clearSession();
+ EncryptionUtility.clearRsaPrivateKeyCache();
// Clear from AsyncStorage (for backward compatibility)
// TODO: Remove AsyncStorage cleanup in future version 0.25.0+
@@ -362,4 +363,4 @@ export const useAuth = (): AuthContextType => {
throw new Error('useAuth must be used within an AuthProvider');
}
return context;
-};
\ No newline at end of file
+};
diff --git a/apps/mobile-app/context/DbContext.tsx b/apps/mobile-app/context/DbContext.tsx
index 6f6359531..3c070f7a6 100644
--- a/apps/mobile-app/context/DbContext.tsx
+++ b/apps/mobile-app/context/DbContext.tsx
@@ -1,6 +1,7 @@
import React, { createContext, useContext, useState, useEffect, useCallback, useMemo } from 'react';
import type { EncryptionKeyDerivationParams, VaultMetadata } from '@/utils/dist/core/models/metadata';
+import EncryptionUtility from '@/utils/EncryptionUtility';
import SqliteClient from '@/utils/SqliteClient';
import NativeVaultManager from '@/specs/NativeVaultManager';
@@ -168,6 +169,7 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }
* Clear database and remove from native module, called when logging out.
*/
const clearDatabase = useCallback(() : void => {
+ EncryptionUtility.clearRsaPrivateKeyCache();
setDbInitialized(false);
NativeVaultManager.clearVault();
}, []);
diff --git a/apps/mobile-app/context/NavigationContext.tsx b/apps/mobile-app/context/NavigationContext.tsx
index 287532386..71a2a5e0f 100644
--- a/apps/mobile-app/context/NavigationContext.tsx
+++ b/apps/mobile-app/context/NavigationContext.tsx
@@ -3,6 +3,7 @@ import React, { createContext, useCallback, useContext, useEffect, useMemo, useR
import { AppState } from 'react-native';
import NativeVaultManager from '@/specs/NativeVaultManager';
+import EncryptionUtility from '@/utils/EncryptionUtility';
type NavigationContextType = {
/**
@@ -190,6 +191,8 @@ export const NavigationProvider: React.FC<{ children: React.ReactNode }> = ({ ch
// Check if vault is unlocked.
const isUnlocked = await isVaultUnlocked();
if (!isUnlocked) {
+ EncryptionUtility.clearRsaPrivateKeyCache();
+
// Get current full URL including query params
const currentRoute = lastRouteRef.current;
if (currentRoute?.path) {
diff --git a/apps/mobile-app/utils/EncryptionUtility.ts b/apps/mobile-app/utils/EncryptionUtility.ts
index bac15fe1a..1ab830869 100644
--- a/apps/mobile-app/utils/EncryptionUtility.ts
+++ b/apps/mobile-app/utils/EncryptionUtility.ts
@@ -13,6 +13,8 @@ import type { Email, MailboxEmail } from '@/utils/dist/core/models/webapi';
* - RSA-OAEP asymmetric encryption/decryption
*/
class EncryptionUtility {
+ private static rsaPrivateKeyCache = new Map<string, Promise<CryptoKey>>();
+
/**
* Derives a key from a password using Argon2Id
*/
@@ -190,33 +192,73 @@ class EncryptionUtility {
*/
public static async decryptWithPrivateKey(ciphertext: string, privateKey: string): Promise<Uint8Array> {
try {
- const privateKeyObj = await crypto.subtle.importKey(
- "jwk",
- JSON.parse(privateKey),
- {
- name: "RSA-OAEP",
- hash: "SHA-256",
- },
- true,
- ["decrypt"]
- );
+ const privateKeyObj = await EncryptionUtility.importPrivateKey(privateKey);
- const cipherBuffer = Uint8Array.from(atob(ciphertext), c => c.charCodeAt(0));
- const plaintextBuffer = await crypto.subtle.decrypt(
- {
- name: "RSA-OAEP",
- },
- privateKeyObj,
- cipherBuffer
- );
-
- return new Uint8Array(plaintextBuffer);
+ return await EncryptionUtility.decryptWithPrivateKeyObject(ciphertext, privateKeyObj);
} catch (error) {
console.error('RSA decryption failed:', error);
throw new Error(`Failed to decrypt: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
+ /**
+ * Decrypts data using RSA-OAEP asymmetric encryption with a CryptoKey private key.
+ */
+ public static async decryptWithPrivateKeyObject(ciphertext: string, privateKey: CryptoKey): Promise<Uint8Array> {
+ const cipherBuffer = Uint8Array.from(atob(ciphertext), c => c.charCodeAt(0));
+ const plaintextBuffer = await crypto.subtle.decrypt(
+ {
+ name: "RSA-OAEP",
+ },
+ privateKey,
+ cipherBuffer
+ );
+
+ return new Uint8Array(plaintextBuffer);
+ }
+
+ /**
+ * Clears cached RSA private keys when the in-memory vault is locked or reset.
+ */
+ public static clearRsaPrivateKeyCache(): void {
+ EncryptionUtility.rsaPrivateKeyCache.clear();
+ }
+
+ /**
+ * Imports an RSA-OAEP private key as non-extractable.
+ */
+ private static async importPrivateKey(privateKey: string): Promise<CryptoKey> {
+ return await crypto.subtle.importKey(
+ "jwk",
+ JSON.parse(privateKey),
+ {
+ name: "RSA-OAEP",
+ hash: "SHA-256",
+ },
+ false,
+ ["decrypt"]
+ );
+ }
+
+ /**
+ * Returns the cached non-extractable private key matching an email encryption public key.
+ */
+ private static async getPrivateKeyObject(encryptionKey: EncryptionKey): Promise<CryptoKey> {
+ const cachedPrivateKey = EncryptionUtility.rsaPrivateKeyCache.get(encryptionKey.PublicKey);
+
+ if (cachedPrivateKey) {
+ return await cachedPrivateKey;
+ }
+
+ const privateKey = EncryptionUtility.importPrivateKey(encryptionKey.PrivateKey).catch(error => {
+ EncryptionUtility.rsaPrivateKeyCache.delete(encryptionKey.PublicKey);
+ throw error;
+ });
+
+ EncryptionUtility.rsaPrivateKeyCache.set(encryptionKey.PublicKey, privateKey);
+ return await privateKey;
+ }
+
/**
* Decrypts an individual email based on the provided public/private key pairs.
*/
@@ -232,9 +274,10 @@ class EncryptionUtility {
}
// Decrypt symmetric key with asymmetric private key
- const symmetricKey = await EncryptionUtility.decryptWithPrivateKey(
+ const privateKey = await EncryptionUtility.getPrivateKeyObject(encryptionKey);
+ const symmetricKey = await EncryptionUtility.decryptWithPrivateKeyObject(
email.encryptedSymmetricKey,
- encryptionKey.PrivateKey
+ privateKey
);
const symmetricKeyBase64 = Buffer.from(symmetricKey).toString('base64');
@@ -276,9 +319,10 @@ class EncryptionUtility {
}
// Decrypt symmetric key with asymmetric private key
- const symmetricKey = await EncryptionUtility.decryptWithPrivateKey(
+ const privateKey = await EncryptionUtility.getPrivateKeyObject(encryptionKey);
+ const symmetricKey = await EncryptionUtility.decryptWithPrivateKeyObject(
email.encryptedSymmetricKey,
- encryptionKey.PrivateKey
+ privateKey
);
const symmetricKeyBase64 = Buffer.from(symmetricKey).toString('base64');
@@ -319,9 +363,10 @@ class EncryptionUtility {
}
// Decrypt the symmetric key using private key (returns raw bytes)
- const symmetricKey = await EncryptionUtility.decryptWithPrivateKey(
+ const privateKey = await EncryptionUtility.getPrivateKeyObject(encryptionKey);
+ const symmetricKey = await EncryptionUtility.decryptWithPrivateKeyObject(
email.encryptedSymmetricKey,
- encryptionKey.PrivateKey
+ privateKey
);
// Convert symmetric key to base64 string if symmetricDecrypt expects it