Skip to content

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

Move RSA keypair generation to Rust crypto layer

Leendert de Borste4447ad3ed67
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.kt
index 99f9ea6c1..38e9dc00e 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
@@ -100,7 +100,7 @@ object RustCoreDispatcher {
"deriveSrpPasswordHash" -> json(deriveSrpPasswordHash(args.bytes(0), args.string(1)))
"openKeyChainWithUnlockKey" -> keyChainResult { openKeyChainWithUnlockKey(args.bytes(0), args.string(1), args.string(2), args.optionalString(3)) }
"openKeyChainWithAccountKey" -> keyChainResult { openKeyChainWithAccountKey(args.bytes(0), args.string(1), args.optionalString(2)) }
- "createAccountKeyHierarchyJson" -> createAccountKeyHierarchyJson(args.bytes(0), args.string(1), args.string(2))
+ "createAccountKeyHierarchyJson" -> createAccountKeyHierarchyJson(args.bytes(0))
"reencryptAccountKeyJson" -> reencryptAccountKeyJson(args.string(0), args.bytes(1), args.bytes(2))
"srpGenerateSalt" -> json(srpGenerateSalt())
diff --git a/apps/mobile-app/ios/NativeVaultManager/NativeVaultManager.swift b/apps/mobile-app/ios/NativeVaultManager/NativeVaultManager.swift
index 57c9c2339..4d03bac16 100644
--- a/apps/mobile-app/ios/NativeVaultManager/NativeVaultManager.swift
+++ b/apps/mobile-app/ios/NativeVaultManager/NativeVaultManager.swift
@@ -1578,7 +1578,7 @@ private enum RustCoreDispatcher {
case "openKeyChainWithAccountKey":
return try keyChainResult { try RustCoreFramework.openKeyChainWithAccountKey(accountKey: try args.data(0), encryptedVek: try args.string(1), encryptedAccountPrivateKey: args.optionalString(2)) }
case "createAccountKeyHierarchyJson":
- return try RustCoreFramework.createAccountKeyHierarchyJson(unlockKey: try args.data(0), publicKeyJwk: try args.string(1), privateKeyJwk: try args.string(2))
+ return try RustCoreFramework.createAccountKeyHierarchyJson(unlockKey: try args.data(0))
case "reencryptAccountKeyJson":
return try RustCoreFramework.reencryptAccountKeyJson(encryptedAccountKey: try args.string(0), oldUnlockKey: try args.data(1), newUnlockKey: try args.data(2))
diff --git a/apps/mobile-app/platform/NativeRustCore.ts b/apps/mobile-app/platform/NativeRustCore.ts
index d7adc3177..edb4977ae 100644
--- a/apps/mobile-app/platform/NativeRustCore.ts
+++ b/apps/mobile-app/platform/NativeRustCore.ts
@@ -34,6 +34,7 @@ function notImplementedOnMobile(name: string, reason: string): Promise<never> {
}
const PIN_IS_NATIVE = 'PIN unlock runs in the native VaultStore';
+const MOBILE_LOGIN_IS_WEB = 'the mobile app approves a mobile login, only the web app and the browser extension request one';
/*
* The client core's Rust binding on mobile: the uniffi Swift/Kotlin bindings, reached through the one generic
@@ -70,11 +71,13 @@ export const nativeRustCore: IRustCore = {
symmetricDecrypt: (base64Ciphertext, keyBase64) => call('symmetricDecrypt', base64Ciphertext, keyBase64),
symmetricDecryptBytes: (encrypted, keyBase64) => callForBytes('symmetricDecryptBytes', base64(encrypted), keyBase64),
symmetricEncryptBytes: (plaintext, keyBase64) => callForBytes('symmetricEncryptBytes', base64(plaintext), keyBase64),
+ generateRsaKeyPair: () => notImplementedOnMobile('generateRsaKeyPair', MOBILE_LOGIN_IS_WEB),
rsaDecrypt: (base64Ciphertext, privateKeyJwk) => callForBytes('rsaDecrypt', base64Ciphertext, privateKeyJwk),
decryptManifestInvitationName: () => notImplementedOnMobile('decryptManifestInvitationName', 'the account private key stays in the native VaultStore, use NativeVaultManager.decryptManifestInvitationName'),
accountSigningKeyFingerprint: () => notImplementedOnMobile('accountSigningKeyFingerprint', 'the Account Key stays in the native VaultStore, use NativeVaultManager.getSigningKeyFingerprint'),
mobileLoginPublicKeyHash: (publicKeyJwk) => call('mobileLoginPublicKeyHash', publicKeyJwk),
mobileLoginVerificationCode: (publicKeyJwk) => call('mobileLoginVerificationCode', publicKeyJwk),
+ mobileLoginOpenApproval: () => notImplementedOnMobile('mobileLoginOpenApproval', MOBILE_LOGIN_IS_WEB),
pinGenerateSalt: () => notImplementedOnMobile('pinGenerateSalt', PIN_IS_NATIVE),
pinEncrypt: () => notImplementedOnMobile('pinEncrypt', PIN_IS_NATIVE),
@@ -86,7 +89,7 @@ export const nativeRustCore: IRustCore = {
deriveSrpPasswordHash: (unlockKeyBase64, encryptionType) => call('deriveSrpPasswordHash', unlockKeyBase64, encryptionType),
openKeyChainWithUnlockKey: (unlockKey, encryptedAccountKey, encryptedVek, encryptedAccountPrivateKey) => call('openKeyChainWithUnlockKey', unlockKey, encryptedAccountKey, encryptedVek, encryptedAccountPrivateKey),
openKeyChainWithAccountKey: (accountKey, encryptedVek, encryptedAccountPrivateKey) => call('openKeyChainWithAccountKey', accountKey, encryptedVek, encryptedAccountPrivateKey),
- createAccountKeyHierarchy: (unlockKeyBase64, publicKeyJwk, privateKeyJwk) => call('createAccountKeyHierarchyJson', unlockKeyBase64, publicKeyJwk, privateKeyJwk),
+ createAccountKeyHierarchy: (unlockKeyBase64) => call('createAccountKeyHierarchyJson', unlockKeyBase64),
reencryptAccountKey: (encryptedAccountKey, oldUnlockKeyBase64, newUnlockKeyBase64) => call('reencryptAccountKeyJson', encryptedAccountKey, oldUnlockKeyBase64, newUnlockKeyBase64),
srpGenerateSalt: () => call('srpGenerateSalt'),
diff --git a/apps/server/Tests/Shared/TestDecryption.cs b/apps/server/Tests/Shared/TestDecryption.cs
index c85af6200..704b83cbe 100644
--- a/apps/server/Tests/Shared/TestDecryption.cs
+++ b/apps/server/Tests/Shared/TestDecryption.cs
@@ -21,7 +21,8 @@ using Org.BouncyCastle.Security;
public static class TestDecryption
{
/// <summary>
- /// Decrypts a symmetric key encrypted with <see cref="Encryption.EncryptSymmetricKeyWithRsa(byte[], string)"/> (BCL RSA-OAEP-SHA256, no label).
+ /// Decrypts a symmetric key encrypted with <see cref="Encryption.EncryptSymmetricKeyWithRsa(byte[], string)"/> with the
+ /// .NET RSA-OAEP-SHA256 (no label), so the test checks the BouncyCastle encryption against a second implementation.
/// </summary>
/// <param name="ciphertext">The encrypted symmetric key as base64.</param>
/// <param name="privateKey">The RSA private key in JWK format.</param>
diff --git a/apps/server/Utilities/AliasVault.Cryptography/Encryption.cs b/apps/server/Utilities/AliasVault.Cryptography/Encryption.cs
index e67daa401..ebcfd13de 100644
--- a/apps/server/Utilities/AliasVault.Cryptography/Encryption.cs
+++ b/apps/server/Utilities/AliasVault.Cryptography/Encryption.cs
@@ -18,7 +18,8 @@ using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
/// <summary>
-/// RSA/AES and Argon2id encryption methods.
+/// The server's encryption: AES-256-GCM (.NET) over email contents and RSA-OAEP-SHA256 (BouncyCastle, for the label
+/// support) of the symmetric keys for client public keys. The server never holds a private key.
/// </summary>
public static class Encryption
{
@@ -38,25 +39,20 @@ public static class Encryption
}
/// <summary>
- /// Encrypts a symmetric key using an RSA public key.
+ /// Encrypts a symmetric key for the holder of an RSA public key with RSA-OAEP-SHA256 and no label: the format every
+ /// email key is stored in.
/// </summary>
/// <param name="symmetricKey">The symmetric key to encrypt.</param>
/// <param name="publicKey">The RSA public key in JWK format.</param>
/// <returns>The encrypted symmetric key as a base64-encoded string.</returns>
public static string EncryptSymmetricKeyWithRsa(byte[] symmetricKey, string publicKey)
{
- using (var rsa = RSA.Create())
- {
- ImportPublicKey(rsa, publicKey);
- var rsaParams = RSAEncryptionPadding.OaepSHA256;
-
- byte[] encryptedKey = rsa.Encrypt(symmetricKey, rsaParams);
- return Convert.ToBase64String(encryptedKey);
- }
+ return EncryptSymmetricKeyWithRsa(symmetricKey, publicKey, string.Empty);
}
/// <summary>
- /// Encrypts a symmetric key using an RSA public key under an OAEP label, which decryption must present as-is.
+ /// Encrypts a symmetric key for the holder of an RSA public key with RSA-OAEP-SHA256 under an OAEP label, which
+ /// decryption must present as-is. An empty label is plain RSA-OAEP-SHA256.
/// </summary>
/// <param name="symmetricKey">The symmetric key to encrypt.</param>
/// <param name="publicKey">The RSA public key in JWK format.</param>
@@ -131,6 +127,10 @@ public static class Encryption
{
int nonceSize = AesGcm.NonceByteSizes.MaxSize;
int tagSize = AesGcm.TagByteSizes.MaxSize;
+ if (encryptedBytes.Length < nonceSize + tagSize)
+ {
+ throw new CryptographicException("AES-GCM ciphertext is too short.");
+ }
// Extract nonce, ciphertext, and tag
byte[] nonce = new byte[nonceSize];
@@ -178,24 +178,4 @@ public static class Encryption
{
return Base64Url.DecodeFromChars(value.Replace('+', '-').Replace('/', '_').TrimEnd('='));
}
-
- /// <summary>
- /// Imports a public key from JWK format into an RSA provider.
- /// </summary>
- /// <param name="rsa">The RSA provider to import the key into.</param>
- /// <param name="jwk">The public key in JWK format.</param>
- private static void ImportPublicKey(RSA rsa, string jwk)
- {
- var jwkObj = JsonSerializer.Deserialize<JsonElement>(jwk);
- var n = JwkBytes(jwkObj.GetProperty("n").GetString()!);
- var e = JwkBytes(jwkObj.GetProperty("e").GetString()!);
-
- var rsaParameters = new RSAParameters
- {
- Modulus = n,
- Exponent = e,
- };
-
- rsa.ImportParameters(rsaParameters);
- }
}
diff --git a/core/client/src/auth/MasterPasswordService.ts b/core/client/src/auth/MasterPasswordService.ts
index fc6b6634f..2255c733b 100644
--- a/core/client/src/auth/MasterPasswordService.ts
+++ b/core/client/src/auth/MasterPasswordService.ts
@@ -2,7 +2,6 @@ import { VaultKeyAlgorithm, type KeyRotationInitiateResponse, type PasswordChang
import { AppErrorCode, extractErrorCode } from '../api/errors/AppErrorCodes';
import { StorageKeys } from '../constants/StorageKeys';
-import { EncryptionUtility } from '../crypto/EncryptionUtility';
import { getPlatform } from '../platform/ClientPlatform';
import { reencryptAccountKey } from '../rust/RustCore';
import { VaultSyncHoldReason, withVaultSyncHold } from '../sync/VaultSyncHold';
@@ -205,7 +204,6 @@ export class MasterPasswordService {
await MasterPasswordService.adoptRaisedSettings(challenge, current.unlockKeyBase64, webApi);
await MasterPasswordService.assertPasswordOpensChain(current.unlockKeyBase64);
const next = await SrpAuthService.prepareNewPassword(newPassword, current.srpIdentity);
- const keyPair = await EncryptionUtility.generateRsaKeyPair();
const result = await runRotation({
userId: challenge.userId,
@@ -218,8 +216,6 @@ export class MasterPasswordService {
newVerifier: next.verifier,
newEncryptionType: next.encryptionType,
newEncryptionSettings: next.encryptionSettings,
- newAccountPublicKey: keyPair.publicKey,
- newAccountPrivateKey: keyPair.privateKey,
});
if (result.success && result.accountKey) {
diff --git a/core/client/src/auth/MobileLoginProtocol.ts b/core/client/src/auth/MobileLoginProtocol.ts
index 681648587..f4429f362 100644
--- a/core/client/src/auth/MobileLoginProtocol.ts
+++ b/core/client/src/auth/MobileLoginProtocol.ts
@@ -18,12 +18,6 @@ export class MobileLoginProtocol {
/** Matches `VERIFICATION_CODE_DIGITS` in `core/rust/src/crypto/mobile_login.rs`. */
public static readonly VERIFICATION_CODE_LENGTH = 2;
- /** RSA-OAEP label of the Account Key the mobile app encrypts; matches `MOBILE_LOGIN_ACCOUNT_KEY` in `core/rust/src/crypto/aad.rs`. */
- public static readonly ACCOUNT_KEY_LABEL = 'aliasvault/v1/mobile-login/account-key';
-
- /** RSA-OAEP label of the payload key the server encrypts; matches `MOBILE_LOGIN_PAYLOAD_KEY` in `core/rust/src/crypto/aad.rs`. */
- public static readonly PAYLOAD_KEY_LABEL = 'aliasvault/v1/mobile-login/payload-key';
-
private static readonly REQUEST_ID_PATTERN = /^[0-9a-f]{32}$/;
private static readonly PUBLIC_KEY_HASH_PATTERN = /^[A-Za-z0-9_-]{43}$/;
diff --git a/core/client/src/auth/MobileLoginService.ts b/core/client/src/auth/MobileLoginService.ts
index 3eef47029..7fab2e93e 100644
--- a/core/client/src/auth/MobileLoginService.ts
+++ b/core/client/src/auth/MobileLoginService.ts
@@ -1,8 +1,6 @@
import { VaultKeyAlgorithm, type MobileLoginInitiateResponse, type MobileLoginPayload, type MobileLoginPollResponse } from '@aliasvault/models/webapi';
-import EncryptionUtility from '../crypto/EncryptionUtility';
import { rustCore } from '../rust/RustCore';
-import { bytesToBase64 } from '../utilities/Base64';
import { MobileLoginProtocol } from './MobileLoginProtocol';
@@ -57,7 +55,7 @@ export class MobileLoginService {
private isPollInFlight = false;
private requestId: string | null = null;
private pollSecret: string | null = null;
- private privateKey: CryptoKey | null = null;
+ private privateKeyJwk: string | null = null;
/**
* Create the service.
@@ -72,8 +70,8 @@ export class MobileLoginService {
*/
public async initiate(): Promise<{ qrPayload: string; verificationCode: string }> {
try {
- const { publicKeyJwk, privateKey } = await EncryptionUtility.generateRsaKeyPairNonExtractable();
- this.privateKey = privateKey;
+ const { publicKey: publicKeyJwk, privateKey } = await rustCore().generateRsaKeyPair();
+ this.privateKeyJwk = privateKey;
const response = await this.api.rawFetch('auth/mobile-login/initiate', {
method: 'POST',
@@ -106,7 +104,7 @@ export class MobileLoginService {
* Poll the server until the request is approved, declined or expired. Exactly one of the callbacks is called.
*/
public startPolling(onSuccess: (result: MobileLoginResult) => void, onError: (errorCode: MobileLoginErrorCode) => void): void {
- if (!this.requestId || !this.pollSecret || !this.privateKey) {
+ if (!this.requestId || !this.pollSecret || !this.privateKeyJwk) {
throw new Error('Must call initiate() before starting polling');
}
@@ -152,21 +150,18 @@ export class MobileLoginService {
if (data.status === 'approved' && data.encryptedSymmetricKey && data.encryptedPayload && data.encryptedAccountKey) {
// Capture the key locally.
- const privateKey = this.privateKey!;
+ const privateKeyJwk = this.privateKeyJwk!;
this.cleanup();
- // The mobile app encrypted its Account Key with our public key.
- const accountKey = bytesToBase64(await EncryptionUtility.decryptWithPrivateKeyObject(data.encryptedAccountKey, privateKey, MobileLoginProtocol.ACCOUNT_KEY_LABEL));
-
- // The server encrypted the session payload with a symmetric key, which is encrypted with our public key.
- const symmetricKey = bytesToBase64(await EncryptionUtility.decryptWithPrivateKeyObject(data.encryptedSymmetricKey, privateKey, MobileLoginProtocol.PAYLOAD_KEY_LABEL));
- const payload = JSON.parse(await rustCore().symmetricDecrypt(data.encryptedPayload, symmetricKey)) as MobileLoginPayload;
+ // The mobile app encrypted its Account Key with our public key, the server the key of the session payload.
+ const approval = await rustCore().mobileLoginOpenApproval(privateKeyJwk, data.encryptedAccountKey, data.encryptedSymmetricKey, data.encryptedPayload);
+ const payload = JSON.parse(approval.payload) as MobileLoginPayload;
onSuccess({
username: payload.username,
token: payload.token,
refreshToken: payload.refreshToken,
- accountKey,
+ accountKey: approval.accountKey,
salt: payload.salt,
encryptionType: payload.encryptionType,
encryptionSettings: payload.encryptionSettings,
@@ -201,7 +196,7 @@ export class MobileLoginService {
clearTimeout(this.pollingTimeout);
this.pollingTimeout = null;
}
- this.privateKey = null;
+ this.privateKeyJwk = null;
}
/**
diff --git a/core/client/src/auth/SrpAuthService.ts b/core/client/src/auth/SrpAuthService.ts
index 450cf8080..65ff0f2f1 100644
--- a/core/client/src/auth/SrpAuthService.ts
+++ b/core/client/src/auth/SrpAuthService.ts
@@ -1,13 +1,12 @@
import { AppErrorCode, formatErrorWithCode } from '../api/errors/AppErrorCodes';
import { StorageKeys } from '../constants/StorageKeys';
-import { createAccountKeyHierarchy, type AccountKeyBlobs, type AccountKeyHierarchy } from '../crypto/AccountKeys';
import { getPlatform } from '../platform/ClientPlatform';
-import { argon2DeriveKey, rustCore } from '../rust/RustCore';
+import { argon2DeriveKey, createAccountKeyHierarchy, rustCore } from '../rust/RustCore';
import { bytesToBase64 } from '../utilities/Base64';
import { isWeakerDerivation } from './DerivationSettings';
-import type { SrpEphemeral, SrpSession } from '../rust/RustCoreTypes';
+import type { AccountKeyBlobs, AccountKeyHierarchy, SrpEphemeral, SrpSession } from '../rust/RustCoreTypes';
import type { UnlockKeyDerivationParams } from '@aliasvault/models/metadata';
import type { LegacySrpVerifierUpgrade, LoginResponse } from '@aliasvault/models/webapi';
diff --git a/core/client/src/auth/SrpLoginService.ts b/core/client/src/auth/SrpLoginService.ts
index 83534c56c..3a9cdb5b4 100644
--- a/core/client/src/auth/SrpLoginService.ts
+++ b/core/client/src/auth/SrpLoginService.ts
@@ -4,7 +4,7 @@ import { throwIfServerPredatesV2Api } from '../sync/LegacyStorageModelMigration'
import { SrpAuthService, type LoginCredentials, type SrpClientSession } from './SrpAuthService';
import type { WebApiService } from '../api/WebApiService';
-import type { AccountKeyHierarchy } from '../crypto/AccountKeys';
+import type { AccountKeyHierarchy } from '../rust/RustCoreTypes';
import type { UnlockKeyDerivationParams } from '@aliasvault/models/metadata';
import type { LegacySrpVerifierUpgrade, LoginResponse, TokenModel, ValidateLoginRequest, ValidateLoginRequest2Fa, ValidateLoginResponse } from '@aliasvault/models/webapi';
diff --git a/core/client/src/crypto/AccountKeys.ts b/core/client/src/crypto/AccountKeys.ts
deleted file mode 100644
index 9c1cd8144..000000000
--- a/core/client/src/crypto/AccountKeys.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import { createAccountKeyHierarchy as createHierarchy } from '../rust/RustCore';
-
-import { EncryptionUtility } from './EncryptionUtility';
-
-import type { AccountKeyHierarchy } from '../rust/RustCoreTypes';
-
-export type { AccountKeyBlobs, AccountKeyHierarchy } from '../rust/RustCoreTypes';
-
-/**
- * Create a new account key hierarchy. The keypair comes from WebCrypto, which is far faster than RSA in wasm.
- * @param unlockKey - the unlock key (base64) whose derived KEK encrypts this account's key material
- */
-export async function createAccountKeyHierarchy(unlockKey: string): Promise<AccountKeyHierarchy> {
- const accountKeyPair = await EncryptionUtility.generateRsaKeyPair();
- return createHierarchy(unlockKey, accountKeyPair.publicKey, accountKeyPair.privateKey);
-}
diff --git a/core/client/src/crypto/EncryptionUtility.ts b/core/client/src/crypto/EncryptionUtility.ts
index 2b96ea4ca..4344d6957 100644
--- a/core/client/src/crypto/EncryptionUtility.ts
+++ b/core/client/src/crypto/EncryptionUtility.ts
@@ -1,33 +1,16 @@
-import { argon2DeriveKey } from '../rust/RustCore';
import { base64ToBytes, bytesToBase64 } from '../utilities/Base64';
-import { logDefect } from '../utilities/Diagnostics';
/** AES-GCM IV length in bytes; every AES-GCM payload starts with it. */
const AES_GCM_IV_LENGTH = 12;
/**
- * Utility class for encryption operations including:
- * - Argon2Id key derivation
- * - AES-GCM symmetric encryption/decryption
- * - RSA-OAEP asymmetric encryption/decryption
+ * The WebCrypto operations the web app and the browser extension run outside the Rust core, each for a reason:
+ * - AES-256-GCM over the local vault blob and email fields: hardware accelerated, where wasm AES is not
+ * (the format is the Rust `aes_gcm.rs` format)
+ * - RSA-OAEP decryption of email keys with an imported non-extractable private key, at WebCrypto speed
+ * Everything else (Argon2id, the key chain, RSA key pair generation, SRP, signing, PIN wrap) runs in the Rust core only.
*/
export class EncryptionUtility {
- /**
- * Derives a key from a password using Argon2Id
- */
- public static async deriveKeyFromPassword(
- password: string,
- salt: string,
- encryptionSettings: string
- ): Promise<Uint8Array> {
- try {
- return await argon2DeriveKey(password, salt, encryptionSettings);
- } catch (error) {
- logDefect('[Crypto] Argon2 hashing failed', error);
- throw error;
- }
- }
-
/**
* Encrypts bytes with AES-256-GCM (random 12-byte IV, no AAD) into base64 `IV | ciphertext | tag`.
*/
@@ -59,38 +42,10 @@ export class EncryptionUtility {
}
/**
- * Generates an extractable RSA-OAEP-2048 (SHA-256) key pair, both halves exported as JWK strings.
- */
- public static async generateRsaKeyPair(): Promise<{ publicKey: string, privateKey: string }> {
- const keyPair = await EncryptionUtility.generateRsaOaepKeyPair(true);
- const publicKey = await crypto.subtle.exportKey('jwk', keyPair.publicKey);
- const privateKey = await crypto.subtle.exportKey('jwk', keyPair.privateKey);
-
- return { publicKey: JSON.stringify(publicKey), privateKey: JSON.stringify(privateKey) };
- }
-
- /**
- * Generates an RSA-OAEP-2048 (SHA-256) key pair whose private key stays inside WebCrypto; the public key is a JWK string.
+ * Decrypts data using RSA-OAEP asymmetric encryption with a CryptoKey private key.
*/
- public static async generateRsaKeyPairNonExtractable(): Promise<{ publicKeyJwk: string, privateKey: CryptoKey }> {
- const keyPair = await EncryptionUtility.generateRsaOaepKeyPair(false);
- const publicKey = await crypto.subtle.exportKey('jwk', keyPair.publicKey);
-
- return { publicKeyJwk: JSON.stringify(publicKey), privateKey: keyPair.privateKey };
- }
-
- /**
- * Decrypts data using RSA-OAEP asymmetric encryption with a CryptoKey private key, under an OAEP label when given.
- */
- public static async decryptWithPrivateKeyObject(ciphertext: string, privateKey: CryptoKey, label?: string): Promise<Uint8Array> {
- const cipherBuffer = base64ToBytes(ciphertext);
- const plaintextBuffer = await crypto.subtle.decrypt(
- label === undefined ? { name: "RSA-OAEP" } : { name: "RSA-OAEP", label: new TextEncoder().encode(label) },
- privateKey,
- cipherBuffer
- );
-
- return new Uint8Array(plaintextBuffer);
+ public static async decryptWithPrivateKeyObject(ciphertext: string, privateKey: CryptoKey): Promise<Uint8Array> {
+ return new Uint8Array(await crypto.subtle.decrypt({ name: 'RSA-OAEP' }, privateKey, base64ToBytes(ciphertext)));
}
/**
@@ -106,17 +61,6 @@ export class EncryptionUtility {
private static async importAesKey(base64Key: string, usage: 'encrypt' | 'decrypt'): Promise<CryptoKey> {
return await crypto.subtle.importKey('raw', base64ToBytes(base64Key), { name: 'AES-GCM', length: 256 }, false, [usage]);
}
-
- /**
- * Generates an RSA-OAEP-2048 key pair with SHA-256 and exponent 65537.
- */
- private static async generateRsaOaepKeyPair(extractable: boolean): Promise<CryptoKeyPair> {
- return await crypto.subtle.generateKey(
- { name: 'RSA-OAEP', modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: 'SHA-256' },
- extractable,
- ['encrypt', 'decrypt']
- );
- }
}
export default EncryptionUtility;
diff --git a/core/client/src/rust/RustCore.ts b/core/client/src/rust/RustCore.ts
index 1f0723690..7caea14ad 100644
--- a/core/client/src/rust/RustCore.ts
+++ b/core/client/src/rust/RustCore.ts
@@ -231,10 +231,10 @@ export async function openKeyChainWithAccountKey(accountKey: string, encryptedVe
}
/**
- * Create a new account key hierarchy for the unlock key (base64) around an account keypair (JWK) the caller generated.
+ * Create a new account key hierarchy for the unlock key (base64).
*/
-export async function createAccountKeyHierarchy(unlockKeyBase64: string, publicKeyJwk: string, privateKeyJwk: string): Promise<AccountKeyHierarchy> {
- return rustCore().createAccountKeyHierarchy(unlockKeyBase64, publicKeyJwk, privateKeyJwk);
+export async function createAccountKeyHierarchy(unlockKeyBase64: string): Promise<AccountKeyHierarchy> {
+ return rustCore().createAccountKeyHierarchy(unlockKeyBase64);
}
/**
diff --git a/core/client/src/rust/RustCoreBinding.ts b/core/client/src/rust/RustCoreBinding.ts
index 84458dd14..d91631bba 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, PinFailure, ReencryptedAccountKey, SrpEphemeral, SrpSession } from './RustCoreTypes';
+import type { AccountKeyHierarchy, CodecCanonicalized, CodecCanonicalizeInput, FaviconTarget, FilterCredentialsInput, FilterCredentialsOutput, KeyChainOpenResult, MobileLoginApproval, ParsedEmail, PinFailure, ReencryptedAccountKey, RsaKeyPair, SrpEphemeral, SrpSession } from './RustCoreTypes';
/**
* One running operation of the Rust vault sync engine.
@@ -48,11 +48,13 @@ export interface IRustCore {
symmetricDecrypt(base64Ciphertext: string, keyBase64: string): Promise<string>;
symmetricDecryptBytes(encrypted: Uint8Array, keyBase64: string): Promise<Uint8Array>;
symmetricEncryptBytes(plaintext: Uint8Array, keyBase64: string): Promise<Uint8Array>;
+ generateRsaKeyPair(): Promise<RsaKeyPair>;
rsaDecrypt(base64Ciphertext: string, privateKeyJwk: string): Promise<Uint8Array>;
decryptManifestInvitationName(encryptedName: string, manifestId: string, privateKeyJwk: string): Promise<string>;
accountSigningKeyFingerprint(encryptedSigningPrivateKey: string, accountKeyBase64: string): Promise<string>;
mobileLoginPublicKeyHash(publicKeyJwk: string): Promise<string>;
mobileLoginVerificationCode(publicKeyJwk: string): Promise<string>;
+ mobileLoginOpenApproval(privateKeyJwk: string, encryptedAccountKey: string, encryptedPayloadKey: string, encryptedPayload: string): Promise<MobileLoginApproval>;
pinGenerateSalt(): Promise<Uint8Array>;
pinEncrypt(pin: string, salt: Uint8Array, secret: Uint8Array): Promise<Uint8Array>;
@@ -64,7 +66,7 @@ export interface IRustCore {
deriveSrpPasswordHash(unlockKeyBase64: string, encryptionType: string): Promise<string>;
openKeyChainWithUnlockKey(unlockKey: string, encryptedAccountKey: string, encryptedVek: string, encryptedAccountPrivateKey: string | null): Promise<KeyChainOpenResult>;
openKeyChainWithAccountKey(accountKey: string, encryptedVek: string, encryptedAccountPrivateKey: string | null): Promise<KeyChainOpenResult>;
- createAccountKeyHierarchy(unlockKeyBase64: string, publicKeyJwk: string, privateKeyJwk: string): Promise<AccountKeyHierarchy>;
+ createAccountKeyHierarchy(unlockKeyBase64: string): Promise<AccountKeyHierarchy>;
reencryptAccountKey(encryptedAccountKey: string, oldUnlockKeyBase64: string, newUnlockKeyBase64: string): Promise<ReencryptedAccountKey | null>;
srpGenerateSalt(): Promise<string>;
diff --git a/core/client/src/rust/RustCoreTypes.ts b/core/client/src/rust/RustCoreTypes.ts
index cf5b7f5c2..a179908e1 100644
--- a/core/client/src/rust/RustCoreTypes.ts
+++ b/core/client/src/rust/RustCoreTypes.ts
@@ -126,6 +126,18 @@ export type AccountKeyHierarchy = {
accountKeys: AccountKeyBlobs;
};
+/** An RSA-OAEP-256 2048-bit key pair, both halves as JWK strings (the Rust `RsaKeyPair`). */
+export type RsaKeyPair = {
+ publicKey: string;
+ privateKey: string;
+};
+
+/** An opened mobile login approval (the Rust `MobileLoginApproval`): the Account Key (base64) and the session payload JSON. */
+export type MobileLoginApproval = {
+ accountKey: string;
+ payload: string;
+};
+
/** The Account Key (base64) re-encrypted for a new password. */
export type ReencryptedAccountKey = {
accountKey: string;
diff --git a/core/client/src/rust/WasmRustCore.ts b/core/client/src/rust/WasmRustCore.ts
index 8f42f02ee..a2f85228b 100644
--- a/core/client/src/rust/WasmRustCore.ts
+++ b/core/client/src/rust/WasmRustCore.ts
@@ -7,7 +7,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, PinFailure, ReencryptedAccountKey, SrpEphemeral, SrpSession } from './RustCoreTypes';
+import type { AccountKeyHierarchy, CodecCanonicalized, CodecCanonicalizeInput, FaviconTarget, FilterCredentialsInput, FilterCredentialsOutput, KeyChainOpenResult, MobileLoginApproval, ParsedEmail, PinFailure, ReencryptedAccountKey, RsaKeyPair, SrpEphemeral, SrpSession } from './RustCoreTypes';
/**
* Where the host gets the `.wasm` binary from: bytes, or a fetch response for streaming instantiation.
@@ -73,11 +73,14 @@ export function createWasmRustCore(loadWasm: WasmLoader): IRustCore {
symmetricDecrypt: (base64Ciphertext, keyBase64): Promise<string> => ready(() => core.symmetricDecrypt(base64Ciphertext, keyBase64)),
symmetricDecryptBytes: (encrypted, keyBase64): Promise<Uint8Array> => ready(() => core.symmetricDecryptBytes(encrypted, keyBase64)),
symmetricEncryptBytes: (plaintext, keyBase64): Promise<Uint8Array> => ready(() => core.symmetricEncryptBytes(plaintext, keyBase64)),
+ generateRsaKeyPair: (): Promise<RsaKeyPair> => ready(() => core.generateRsaKeyPair() as RsaKeyPair),
rsaDecrypt: (base64Ciphertext, privateKeyJwk): Promise<Uint8Array> => ready(() => core.rsaDecrypt(base64Ciphertext, privateKeyJwk)),
decryptManifestInvitationName: (encryptedName, manifestId, privateKeyJwk): Promise<string> => ready(() => core.decryptManifestInvitationName(encryptedName, manifestId, privateKeyJwk)),
accountSigningKeyFingerprint: (encryptedSigningPrivateKey, accountKeyBase64): Promise<string> => ready(() => core.accountSigningKeyFingerprint(encryptedSigningPrivateKey, accountKeyBase64)),
mobileLoginPublicKeyHash: (publicKeyJwk): Promise<string> => ready(() => core.mobileLoginPublicKeyHash(publicKeyJwk)),
mobileLoginVerificationCode: (publicKeyJwk): Promise<string> => ready(() => core.mobileLoginVerificationCode(publicKeyJwk)),
+ mobileLoginOpenApproval: (privateKeyJwk, encryptedAccountKey, encryptedPayloadKey, encryptedPayload): Promise<MobileLoginApproval> =>
+ ready(() => core.mobileLoginOpenApproval(privateKeyJwk, encryptedAccountKey, encryptedPayloadKey, encryptedPayload) as MobileLoginApproval),
/*
* Argon2 (also behind pinEncrypt and pinDecrypt) blocks the thread it runs on for up to a few seconds on slow
@@ -104,8 +107,7 @@ export function createWasmRustCore(loadWasm: WasmLoader): IRustCore {
ready(() => core.openKeyChainWithUnlockKey(unlockKey, encryptedAccountKey, encryptedVek, encryptedAccountPrivateKey ?? undefined) as KeyChainOpenResult),
openKeyChainWithAccountKey: (accountKey, encryptedVek, encryptedAccountPrivateKey): Promise<KeyChainOpenResult> =>
ready(() => core.openKeyChainWithAccountKey(accountKey, encryptedVek, encryptedAccountPrivateKey ?? undefined) as KeyChainOpenResult),
- createAccountKeyHierarchy: (unlockKeyBase64, publicKeyJwk, privateKeyJwk): Promise<AccountKeyHierarchy> =>
- ready(() => core.createAccountKeyHierarchy(unlockKeyBase64, publicKeyJwk, privateKeyJwk) as AccountKeyHierarchy),
+ createAccountKeyHierarchy: (unlockKeyBase64): Promise<AccountKeyHierarchy> => ready(() => core.createAccountKeyHierarchy(unlockKeyBase64) as AccountKeyHierarchy),
reencryptAccountKey: (encryptedAccountKey, oldUnlockKeyBase64, newUnlockKeyBase64): Promise<ReencryptedAccountKey | null> =>
ready(() => core.reencryptAccountKey(encryptedAccountKey, oldUnlockKeyBase64, newUnlockKeyBase64) as ReencryptedAccountKey | null),
diff --git a/core/client/src/sync/VaultSyncEngine.ts b/core/client/src/sync/VaultSyncEngine.ts
index d9d43e39a..a08d9efa8 100644
--- a/core/client/src/sync/VaultSyncEngine.ts
+++ b/core/client/src/sync/VaultSyncEngine.ts
@@ -37,8 +37,6 @@ export type VaultSyncKeyRotationParams = {
newVerifier: string;
newEncryptionType: string;
newEncryptionSettings: string;
- newAccountPublicKey: string;
- newAccountPrivateKey: string;
};
/** What a sharing operation acts on (the Rust `SharingParams`). */
diff --git a/core/rust/src/bindings/uniffi_api.rs b/core/rust/src/bindings/uniffi_api.rs
index 822bfb914..c368aa7ff 100644
--- a/core/rust/src/bindings/uniffi_api.rs
+++ b/core/rust/src/bindings/uniffi_api.rs
@@ -254,12 +254,11 @@ 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.
+/// Create a new account key hierarchy for the unlock key, as JSON.
#[uniffi::export]
-pub fn create_account_key_hierarchy_json(unlock_key: Vec<u8>, public_key_jwk: String, private_key_jwk: String) -> Result<String, VaultError> {
+pub fn create_account_key_hierarchy_json(unlock_key: Vec<u8>) -> Result<String, VaultError> {
let unlock_key = zeroize::Zeroizing::new(crate::common::encoding::base64_encode(&unlock_key));
- let key_pair = crate::crypto::RsaKeyPair { public_key: public_key_jwk, private_key: private_key_jwk };
- let hierarchy = crate::crypto::create_account_key_hierarchy_with_key_pair(&unlock_key, &key_pair)?;
+ let hierarchy = crate::crypto::create_account_key_hierarchy(&unlock_key)?;
Ok(serde_json::to_string(&hierarchy)?)
}
diff --git a/core/rust/src/bindings/wasm.rs b/core/rust/src/bindings/wasm.rs
index e97002b1b..c89cade88 100644
--- a/core/rust/src/bindings/wasm.rs
+++ b/core/rust/src/bindings/wasm.rs
@@ -234,6 +234,18 @@ pub fn account_signing_key_fingerprint_js(encrypted_signing_private_key: &str, a
crate::crypto::account_signing_key_fingerprint(encrypted_signing_private_key, account_key_base64).map_err(js_err)
}
+/// Open an approved mobile login request with its one-off JWK private key: `{ accountKey, payload }`.
+#[wasm_bindgen(js_name = mobileLoginOpenApproval)]
+pub fn mobile_login_open_approval_js(private_key_jwk: &str, encrypted_account_key: &str, encrypted_payload_key: &str, encrypted_payload: &str) -> Result<JsValue, JsValue> {
+ to_js(&crate::crypto::mobile_login_open_approval(private_key_jwk, encrypted_account_key, encrypted_payload_key, encrypted_payload).map_err(js_err)?)
+}
+
+/// A new RSA-OAEP-256 2048-bit key pair, both halves as JWK strings: `{ publicKey, privateKey }`.
+#[wasm_bindgen(js_name = generateRsaKeyPair)]
+pub fn generate_rsa_key_pair_js() -> Result<JsValue, JsValue> {
+ to_js(&crate::crypto::generate_rsa_key_pair().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> {
@@ -276,11 +288,10 @@ 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.
+/// Create a new account key hierarchy for the base64 unlock key.
#[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> {
- let key_pair = crate::crypto::RsaKeyPair { public_key: public_key_jwk, private_key: private_key_jwk };
- to_js(&crate::crypto::create_account_key_hierarchy_with_key_pair(unlock_key_base64, &key_pair).map_err(js_err)?)
+pub fn create_account_key_hierarchy_js(unlock_key_base64: &str) -> Result<JsValue, JsValue> {
+ to_js(&crate::crypto::create_account_key_hierarchy(unlock_key_base64).map_err(js_err)?)
}
/// Re-encrypt the Account Key from the old to the new base64 unlock key; `null` when the old unlock key does not open it.
diff --git a/core/rust/src/crypto/key_chain.rs b/core/rust/src/crypto/key_chain.rs
index 4eefc7083..4e7d7a231 100644
--- a/core/rust/src/crypto/key_chain.rs
+++ b/core/rust/src/crypto/key_chain.rs
@@ -11,7 +11,7 @@ use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};
use super::aad;
use super::aes_gcm::{generate_key_base64, symmetric_decrypt_bytes_with_aad, symmetric_decrypt_with_aad, symmetric_encrypt_bytes_with_aad, symmetric_encrypt_with_aad};
-use super::rsa_oaep::{generate_rsa_key_pair, validate_rsa_key_pair, RsaKeyPair};
+use super::rsa_oaep::generate_rsa_key_pair;
use super::signing::{self, generate_signing_key_pair};
use super::tokens::{ALGORITHM_AES256_GCM, ENCRYPTION_TYPE_ARGON2ID, ENCRYPTION_TYPE_ARGON2ID_HKDF};
use crate::common::encoding::{base64_decode, base64_encode, hex_encode_upper};
@@ -193,12 +193,7 @@ fn open_optional_account_private_key(encrypted_account_private_key: Option<&str>
/// Create a new account key hierarchy wrapped under the KEK derived from an unlock key.
pub fn create_account_key_hierarchy(unlock_key_base64: &str) -> VaultResult<AccountKeyHierarchy> {
- create_account_key_hierarchy_with_key_pair(unlock_key_base64, &generate_rsa_key_pair()?)
-}
-
-/// [`create_account_key_hierarchy`] around an account keypair the host generated, as WebCrypto is far faster than wasm.
-pub fn create_account_key_hierarchy_with_key_pair(unlock_key_base64: &str, key_pair: &RsaKeyPair) -> VaultResult<AccountKeyHierarchy> {
- validate_rsa_key_pair(key_pair)?;
+ let key_pair = generate_rsa_key_pair()?;
let vault_encryption_key = generate_key_base64();
let account_key = Zeroizing::new(generate_key_base64());
let signing_key_pair = generate_signing_key_pair();
@@ -255,10 +250,10 @@ impl fmt::Debug for RotatedAccountKeys {
}
}
-/// Rotate an account's keys: a new Account Key, VEK and signing keypair around an account keypair the host generated,
-/// wrapped under the KEK of `new_unlock_key_base64`.
-pub fn rotate_account_keys(new_unlock_key_base64: &str, key_pair: &RsaKeyPair) -> VaultResult<RotatedAccountKeys> {
- let hierarchy = create_account_key_hierarchy_with_key_pair(new_unlock_key_base64, key_pair)?;
+/// Rotate an account's keys: a new Account Key, VEK, account keypair and signing keypair, wrapped under the KEK of
+/// `new_unlock_key_base64`.
+pub fn rotate_account_keys(new_unlock_key_base64: &str) -> VaultResult<RotatedAccountKeys> {
+ let hierarchy = create_account_key_hierarchy(new_unlock_key_base64)?;
Ok(RotatedAccountKeys {
account_key: hierarchy.account_key.clone(),
vault_encryption_key: hierarchy.vault_encryption_key.clone(),
diff --git a/core/rust/src/crypto/mobile_login.rs b/core/rust/src/crypto/mobile_login.rs
index e4c047d1d..3ab6bc012 100644
--- a/core/rust/src/crypto/mobile_login.rs
+++ b/core/rust/src/crypto/mobile_login.rs
@@ -1,9 +1,15 @@
-//! The hashes of the mobile login (QR unlock) handshake: the public key hash the QR code carries and the verification
-//! code both devices show.
+//! The mobile login (QR unlock) handshake: the public key hash the QR code carries, the verification code both devices
+//! show, and opening the approval the requesting client collects.
+use serde::Serialize;
use sha2::{Digest, Sha256};
+use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};
-use crate::common::encoding::base64url_encode;
+use super::aad;
+use super::aes_gcm::symmetric_decrypt;
+use super::rsa_oaep::decrypt_with_private_key_and_label;
+use crate::common::encoding::{base64_encode, base64url_encode};
+use crate::common::error::VaultResult;
/// The domain separator hashed in front of the public key for the verification code.
const VERIFICATION_CODE_CONTEXT: &[u8] = b"AliasVault.MobileLogin.VerificationCode.v1:";
@@ -22,3 +28,18 @@ pub fn mobile_login_verification_code(public_key_jwk: &str) -> String {
let value = u32::from_be_bytes([digest[0], digest[1], digest[2], digest[3]]);
format!("{:0width$}", value % 10u32.pow(VERIFICATION_CODE_DIGITS), width = VERIFICATION_CODE_DIGITS as usize)
}
+
+/// An opened mobile login approval: the mobile app's Account Key (base64) and the session payload JSON the server sent.
+#[derive(Serialize, Zeroize, ZeroizeOnDrop)]
+#[serde(rename_all = "camelCase")]
+pub struct MobileLoginApproval {
+ pub account_key: String,
+ pub payload: String,
+}
+
+/// Open an approved mobile login request with the request's one-off JWK private key.
+pub fn mobile_login_open_approval(private_key_jwk: &str, encrypted_account_key: &str, encrypted_payload_key: &str, encrypted_payload: &str) -> VaultResult<MobileLoginApproval> {
+ let account_key = Zeroizing::new(decrypt_with_private_key_and_label(encrypted_account_key, private_key_jwk, aad::MOBILE_LOGIN_ACCOUNT_KEY)?);
+ let payload_key = Zeroizing::new(base64_encode(&Zeroizing::new(decrypt_with_private_key_and_label(encrypted_payload_key, private_key_jwk, aad::MOBILE_LOGIN_PAYLOAD_KEY)?)));
+ Ok(MobileLoginApproval { account_key: base64_encode(&account_key), payload: symmetric_decrypt(encrypted_payload, &payload_key)? })
+}
diff --git a/core/rust/src/crypto/mod.rs b/core/rust/src/crypto/mod.rs
index 479c128ae..1281b2275 100644
--- a/core/rust/src/crypto/mod.rs
+++ b/core/rust/src/crypto/mod.rs
@@ -36,11 +36,11 @@ pub use aes_gcm::{
symmetric_encrypt_raw_with_aad, symmetric_encrypt_with_aad,
};
pub use key_chain::{
- account_signing_key_fingerprint, create_account_key_hierarchy, create_account_key_hierarchy_with_key_pair, derive_srp_password_hash, open_account_private_key, open_account_signing_private_key,
+ account_signing_key_fingerprint, create_account_key_hierarchy, derive_srp_password_hash, open_account_private_key, open_account_signing_private_key,
open_key_chain_with_account_key, open_key_chain_with_unlock_key, reencrypt_account_key, rotate_account_keys, unwrap_account_key, unwrap_key, wrap_key, AccountKeyBlobs, AccountKeyHierarchy, KeyChainError,
RotatedAccountKeys, SrpInputError,
};
-pub use mobile_login::{mobile_login_public_key_hash, mobile_login_verification_code};
+pub use mobile_login::{mobile_login_open_approval, mobile_login_public_key_hash, mobile_login_verification_code, MobileLoginApproval};
pub use pin::{pin_decrypt, pin_encrypt, pin_generate_salt, pin_is_locked, pin_register_failure, PinFailure};
pub use rsa_oaep::{decrypt_manifest_invitation_name, decrypt_with_private_key, decrypt_with_private_key_and_label, encrypt_with_public_key_and_label, generate_rsa_key_pair, RsaKeyPair};
pub use signing::generate_signing_key_pair;
diff --git a/core/rust/src/crypto/tests/key_chain.rs b/core/rust/src/crypto/tests/key_chain.rs
index 15e01d328..82cd39c41 100644
--- a/core/rust/src/crypto/tests/key_chain.rs
+++ b/core/rust/src/crypto/tests/key_chain.rs
@@ -2,7 +2,6 @@ use crate::common::encoding::hex_encode_upper;
use crate::crypto::aad;
use crate::crypto::aes_gcm::{generate_key_base64, symmetric_decrypt_with_aad};
use crate::crypto::key_chain::*;
-use crate::crypto::rsa_oaep::{generate_rsa_key_pair, RsaKeyPair};
use crate::crypto::signing;
use crate::crypto::tokens::{ENCRYPTION_TYPE_ARGON2ID, ENCRYPTION_TYPE_ARGON2ID_HKDF};
@@ -119,35 +118,23 @@ fn a_private_key_that_does_not_open_leaves_grants_closed_but_opens_the_vault() {
fn rotated_keys_open_with_the_new_unlock_key() {
let old_hierarchy = create_account_key_hierarchy(&generate_key_base64()).unwrap();
let new_unlock_key = generate_key_base64();
- let key_pair = generate_rsa_key_pair().unwrap();
- let rotated = rotate_account_keys(&new_unlock_key, &key_pair).unwrap();
+ let rotated = rotate_account_keys(&new_unlock_key).unwrap();
let blobs = &rotated.account_keys;
// The new chain opens with the new unlock key and yields the new VEK and private keys.
let opened = open_key_chain_with_unlock_key(&new_unlock_key, &blobs.encrypted_account_key, &blobs.encrypted_vek, Some(&blobs.encrypted_account_private_key)).unwrap();
assert_eq!(*opened.vault_encryption_key, rotated.vault_encryption_key);
assert_eq!(*opened.account_key, rotated.account_key);
- assert_eq!(opened.account_private_key.as_deref().map(String::as_str), Some(key_pair.private_key.as_str()));
+ assert_eq!(opened.account_private_key.as_deref().map(String::as_str), Some(rotated.account_private_key.as_str()));
assert_ne!(rotated.vault_encryption_key, old_hierarchy.vault_encryption_key);
+ assert_ne!(blobs.account_public_key, old_hierarchy.account_keys.account_public_key);
assert_ne!(blobs.signing_public_key, old_hierarchy.account_keys.signing_public_key);
// The new signing key vouches for the new account public key.
assert!(signing::verify(&blobs.signing_public_key, &signing::account_public_key_message(&blobs.account_public_key), &blobs.account_public_key_signature));
}
-#[test]
-fn hierarchy_takes_a_host_key_pair_and_rejects_a_mismatched_one() {
- let unlock_key = generate_key_base64();
- let key_pair = generate_rsa_key_pair().unwrap();
- let hierarchy = create_account_key_hierarchy_with_key_pair(&unlock_key, &key_pair).unwrap();
- assert_eq!(hierarchy.account_keys.account_public_key, key_pair.public_key);
- assert_eq!(hierarchy.account_private_key, key_pair.private_key);
-
- let mismatched = RsaKeyPair { public_key: generate_rsa_key_pair().unwrap().public_key.clone(), private_key: key_pair.private_key.clone() };
- assert!(create_account_key_hierarchy_with_key_pair(&unlock_key, &mismatched).is_err());
-}
-
#[test]
fn hierarchy_carries_a_signing_key_that_signed_the_account_public_key() {
let unlock_key = generate_key_base64();
diff --git a/core/rust/src/crypto/tests/mobile_login.rs b/core/rust/src/crypto/tests/mobile_login.rs
index f63d12fbb..d193d1a14 100644
--- a/core/rust/src/crypto/tests/mobile_login.rs
+++ b/core/rust/src/crypto/tests/mobile_login.rs
@@ -1,4 +1,7 @@
+use crate::crypto::aad;
+use crate::crypto::aes_gcm::{generate_key_base64, symmetric_encrypt};
use crate::crypto::mobile_login::*;
+use crate::crypto::rsa_oaep::{encrypt_with_public_key_and_label, generate_rsa_key_pair};
/// Known-answer vectors from the former TypeScript implementation, which released clients still run. A changed output
/// means an old and a new client no longer agree on the QR code or the code they show. Never regenerate them.
@@ -10,3 +13,20 @@ fn known_answers() {
assert_eq!(mobile_login_public_key_hash("héllo ✓"), "VlfN74qFpYTg6WHm-CR89dP47SFJbtb9vP1Dp2HpQkU");
assert_eq!(mobile_login_verification_code("héllo ✓"), "39");
}
+
+#[test]
+fn approval_opens_with_the_request_key_and_rejects_swapped_labels() {
+ let pair = generate_rsa_key_pair().unwrap();
+ let account_key = [7u8; 32];
+ let payload_key = generate_key_base64();
+ let encrypted_account_key = encrypt_with_public_key_and_label(&account_key, &pair.public_key, aad::MOBILE_LOGIN_ACCOUNT_KEY).unwrap();
+ let encrypted_payload_key = encrypt_with_public_key_and_label(&crate::common::encoding::base64_decode(&payload_key).unwrap(), &pair.public_key, aad::MOBILE_LOGIN_PAYLOAD_KEY).unwrap();
+ let encrypted_payload = symmetric_encrypt(r#"{"username":"u"}"#, &payload_key).unwrap();
+
+ let approval = mobile_login_open_approval(&pair.private_key, &encrypted_account_key, &encrypted_payload_key, &encrypted_payload).unwrap();
+ assert_eq!(approval.account_key, crate::common::encoding::base64_encode(&account_key));
+ assert_eq!(approval.payload, r#"{"username":"u"}"#);
+
+ // Each ciphertext only opens under its own label.
+ assert!(mobile_login_open_approval(&pair.private_key, &encrypted_payload_key, &encrypted_account_key, &encrypted_payload).is_err());
+}
diff --git a/core/rust/src/vault_sync/rotation.rs b/core/rust/src/vault_sync/rotation.rs
index 94c15e9eb..bea576327 100644
--- a/core/rust/src/vault_sync/rotation.rs
+++ b/core/rust/src/vault_sync/rotation.rs
@@ -197,8 +197,7 @@ async fn rotate(ctx: &mut Ctx) -> Outcome {
let blob_keys: BlobKeysResponse = http::with_outdated_server_guard(http::get(&ctx.host, &format!("Vault/blob-keys/{}", personal_manifest_id), false).await)?;
let certifications: Vec<CertificationEntry> = http::with_outdated_server_guard(http::get(&ctx.host, "Groups/certifications", false).await)?;
- let key_pair = crypto::RsaKeyPair { public_key: params.new_account_public_key.clone(), private_key: params.new_account_private_key.expose_secret().to_string() };
- let rotated = crypto::rotate_account_keys(params.new_unlock_key.expose_secret(), &key_pair)?;
+ let rotated = crypto::rotate_account_keys(params.new_unlock_key.expose_secret())?;
let new_vek = SecretString::from(rotated.vault_encryption_key.as_str());
ctx.log("[KeyRotation] Generated the new Account Key, VEK, account keypair and signing keypair.").await;
diff --git a/core/rust/src/vault_sync/types.rs b/core/rust/src/vault_sync/types.rs
index c70698ebd..cd34baec6 100644
--- a/core/rust/src/vault_sync/types.rs
+++ b/core/rust/src/vault_sync/types.rs
@@ -45,8 +45,7 @@ pub enum SyncOperation {
}
/// What a key rotation needs from the host: the proof of the current password and the new unlock method, both
-/// derived from the master password on the host, and the new account keypair (WebCrypto generates RSA keys far
-/// faster than wasm).
+/// derived from the master password on the host.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct KeyRotationParams {
@@ -60,8 +59,6 @@ pub struct KeyRotationParams {
pub new_verifier: String,
pub new_encryption_type: String,
pub new_encryption_settings: String,
- pub new_account_public_key: String,
- pub new_account_private_key: SecretString,
}
/// What a sharing operation acts on.