Skip to content

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

Refactor manifest invite name decryption logic

Leendert de Borst540c3542dbd9
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt
index e9ac7c817..4b02f9d7d 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt
@@ -343,11 +343,12 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :
/**
* Decrypt an invitation's vault name with the session account private key; null when the session holds none that opens it.
* @param encryptedName The base64 RSA-OAEP ciphertext of the name
+ * @param manifestId The shared manifest the invitation is for
* @param promise The promise to resolve
*/
@ReactMethod
- override fun decryptInvitationName(encryptedName: String, promise: Promise) {
- promise.resolve(vaultStore.decryptWithAccountPrivateKey(encryptedName))
+ override fun decryptManifestInvitationName(encryptedName: String, manifestId: String, promise: Promise) {
+ promise.resolve(vaultStore.decryptManifestInvitationName(encryptedName, manifestId))
}
/**
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.kt
index ac6e36635..4651811f7 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
@@ -21,7 +21,7 @@ import uniffi.aliasvault_core.ItemUsageAction
import uniffi.aliasvault_core.VaultException
import uniffi.aliasvault_core.VaultItem
import uniffi.aliasvault_core.accountSigningKeyFingerprint
-import uniffi.aliasvault_core.rsaDecrypt
+import uniffi.aliasvault_core.decryptManifestInvitationName as rustDecryptManifestInvitationName
import java.util.Date
import java.util.UUID
import kotlin.coroutines.resume
@@ -280,15 +280,15 @@ class VaultStore(
}
/**
- * Decrypt base64 RSA-OAEP ciphertext with the session's account private key as UTF-8 text, or null when the session
- * holds no private key or it does not open the ciphertext.
+ * Decrypt an invitation's vault name with the session's account private key, or null when the session holds no private
+ * key or it does not open the name.
*/
- fun decryptWithAccountPrivateKey(base64Ciphertext: String): String? {
+ fun decryptManifestInvitationName(encryptedName: String, manifestId: String): String? {
val privateKey = accountPrivateKey ?: return null
return try {
- rsaDecrypt(base64Ciphertext, privateKey).toString(Charsets.UTF_8)
+ rustDecryptManifestInvitationName(encryptedName, manifestId, privateKey)
} catch (e: VaultException) {
- Log.w(TAG, "The account private key did not open the ciphertext", e)
+ Log.w(TAG, "The account private key did not open the invitation name", e)
null
}
}
diff --git a/apps/mobile-app/hooks/useSharedFolders.ts b/apps/mobile-app/hooks/useSharedFolders.ts
index 9098f58bc..5b0edc175 100644
--- a/apps/mobile-app/hooks/useSharedFolders.ts
+++ b/apps/mobile-app/hooks/useSharedFolders.ts
@@ -1,5 +1,5 @@
import { sharingView, type SharedFolder } from '@aliasvault/client/sharing/SharingView';
-import { SharingService } from '@aliasvault/client/sharing/SharingService';
+import { SharingService, type InvitationNameDecryptor } from '@aliasvault/client/sharing/SharingService';
import { CapabilityKeys } from '@aliasvault/models/webapi';
import { useFocusEffect } from 'expo-router';
import { useCallback, useEffect, useState } from 'react';
@@ -12,6 +12,9 @@ import NativeVaultManager from '@/specs/NativeVaultManager';
import type { GroupMemberInfo, ReceivedManifestInvitation } from '@aliasvault/models/webapi';
+/** Decrypts an invitation's vault name natively, where the account private key lives. */
+const decryptNameNatively: InvitationNameDecryptor = (encryptedName, manifestId) => NativeVaultManager.decryptManifestInvitationName(encryptedName, manifestId);
+
/**
* What the vault shows of sharing: the shared folders with their people, the invitations waiting for an answer, the
* people verified before and this account's own fingerprint.
@@ -44,7 +47,7 @@ export function useSharedFolders(): SharedFolders {
try {
const overview = await SharingService.getOverview(webApi);
setView(sharingView(overview));
- setInvitationNames(await SharingService.openInvitationNames(overview.receivedInvitations, encryptedName => NativeVaultManager.decryptInvitationName(encryptedName)));
+ setInvitationNames(await SharingService.openInvitationNames(overview.receivedInvitations, decryptNameNatively));
// The own fingerprint is derived natively from the signing private key, which only the native layer can open.
setOwnFingerprint(await NativeVaultManager.getSigningKeyFingerprint());
} catch {
diff --git a/apps/mobile-app/ios/NativeVaultManager/NativeVaultManager.swift b/apps/mobile-app/ios/NativeVaultManager/NativeVaultManager.swift
index 423ef2a48..303274884 100644
--- a/apps/mobile-app/ios/NativeVaultManager/NativeVaultManager.swift
+++ b/apps/mobile-app/ios/NativeVaultManager/NativeVaultManager.swift
@@ -136,10 +136,11 @@ public class NativeVaultManager: NSObject {
/// Decrypt an invitation's vault name with the session account private key; nil when the session holds none that opens it.
@objc
- func decryptInvitationName(_ encryptedName: String,
+ func decryptManifestInvitationName(_ encryptedName: String,
+ manifestId: String,
resolver resolve: @escaping RCTPromiseResolveBlock,
rejecter reject: @escaping RCTPromiseRejectBlock) {
- resolve(vaultStore.decryptWithAccountPrivateKey(encryptedName))
+ resolve(vaultStore.decryptManifestInvitationName(encryptedName, manifestId: manifestId))
}
/// The account fingerprint of the account's own signing key; nil while locked or when the account has no signing key yet.
diff --git a/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm b/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm
index e140215e9..c86b5a6d4 100644
--- a/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm
+++ b/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm
@@ -129,8 +129,8 @@
[vaultManager getPersonalManifestId:resolve rejecter:reject];
}
-- (void)decryptInvitationName:(NSString *)encryptedName resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
- [vaultManager decryptInvitationName:encryptedName resolver:resolve rejecter:reject];
+- (void)decryptManifestInvitationName:(NSString *)encryptedName manifestId:(NSString *)manifestId resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
+ [vaultManager decryptManifestInvitationName:encryptedName manifestId:manifestId resolver:resolve rejecter:reject];
}
- (void)getSigningKeyFingerprint:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift
index eca7eb58b..6884c6e1c 100644
--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Crypto.swift
@@ -139,13 +139,13 @@ extension VaultStore {
}
}
- /// Decrypt base64 RSA-OAEP ciphertext with the session's account private key as UTF-8 text, or nil when the session holds
- /// no private key or it does not open the ciphertext.
- public func decryptWithAccountPrivateKey(_ base64Ciphertext: String) -> String? {
- guard let privateKey = accountPrivateKey, let plaintext = try? RustCoreFramework.rsaDecrypt(base64Ciphertext: base64Ciphertext, privateKeyJwk: privateKey) else {
+ /// Decrypt an invitation's vault name with the session's account private key, or nil when the session holds no private key
+ /// or it does not open the name.
+ public func decryptManifestInvitationName(_ encryptedName: String, manifestId: String) -> String? {
+ guard let privateKey = accountPrivateKey else {
return nil
}
- return String(data: plaintext, encoding: .utf8)
+ return try? RustCoreFramework.decryptManifestInvitationName(encryptedName: encryptedName, manifestId: manifestId, privateKeyJwk: privateKey)
}
/// The account fingerprint of the account's own signing key, derived from the private key the sync engine cached, or nil
diff --git a/apps/mobile-app/platform/NativeRustCore.ts b/apps/mobile-app/platform/NativeRustCore.ts
index 1fb08a657..ebcbe9d5b 100644
--- a/apps/mobile-app/platform/NativeRustCore.ts
+++ b/apps/mobile-app/platform/NativeRustCore.ts
@@ -71,6 +71,7 @@ export const nativeRustCore: IRustCore = {
symmetricDecryptBytes: (encrypted, keyBase64) => callForBytes('symmetricDecryptBytes', base64(encrypted), keyBase64),
symmetricEncryptBytes: (plaintext, keyBase64) => callForBytes('symmetricEncryptBytes', base64(plaintext), keyBase64),
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'),
pinGenerateSalt: () => notImplementedOnMobile('pinGenerateSalt', PIN_IS_NATIVE),
diff --git a/apps/mobile-app/specs/NativeVaultManager.ts b/apps/mobile-app/specs/NativeVaultManager.ts
index 975a33be7..0c56a9487 100644
--- a/apps/mobile-app/specs/NativeVaultManager.ts
+++ b/apps/mobile-app/specs/NativeVaultManager.ts
@@ -71,7 +71,7 @@ export interface Spec extends TurboModule {
getAccountKeyChain(): Promise<string | null>;
resolveVaultKey(base64DerivedKey: string): Promise<void>;
getPersonalManifestId(): Promise<string | null>;
- decryptInvitationName(encryptedName: string): Promise<string | null>;
+ decryptManifestInvitationName(encryptedName: string, manifestId: string): Promise<string | null>;
getSigningKeyFingerprint(): Promise<string | null>;
hasEncryptedDatabase(): Promise<boolean>;
diff --git a/core/client/src/crypto/EncryptionUtility.ts b/core/client/src/crypto/EncryptionUtility.ts
index 326dcb13f..969db7eea 100644
--- a/core/client/src/crypto/EncryptionUtility.ts
+++ b/core/client/src/crypto/EncryptionUtility.ts
@@ -101,20 +101,6 @@ export class EncryptionUtility {
return { publicKeyJwk: JSON.stringify(publicKey), privateKey: keyPair.privateKey };
}
- /**
- * Decrypts data using RSA-OAEP asymmetric encryption with a JWK private key
- */
- public static async decryptWithPrivateKey(ciphertext: string, privateKey: string): Promise<Uint8Array> {
- try {
- const privateKeyObj = await EncryptionUtility.importPrivateKey(privateKey);
-
- return await EncryptionUtility.decryptWithPrivateKeyObject(ciphertext, privateKeyObj);
- } catch (error) {
- logDefect('[Crypto] 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, under an OAEP label when given.
*/
diff --git a/core/client/src/rust/RustCoreBinding.ts b/core/client/src/rust/RustCoreBinding.ts
index 14e1ec947..665458f9b 100644
--- a/core/client/src/rust/RustCoreBinding.ts
+++ b/core/client/src/rust/RustCoreBinding.ts
@@ -49,6 +49,7 @@ export interface IRustCore {
symmetricDecryptBytes(encrypted: Uint8Array, keyBase64: string): Promise<Uint8Array>;
symmetricEncryptBytes(plaintext: Uint8Array, keyBase64: string): Promise<Uint8Array>;
rsaDecrypt(base64Ciphertext: string, privateKeyJwk: string): Promise<Uint8Array>;
+ decryptManifestInvitationName(encryptedName: string, manifestId: string, privateKeyJwk: string): Promise<string>;
accountSigningKeyFingerprint(encryptedSigningPrivateKey: string, accountKeyBase64: string): Promise<string>;
pinGenerateSalt(): Promise<Uint8Array>;
diff --git a/core/client/src/rust/WasmRustCore.ts b/core/client/src/rust/WasmRustCore.ts
index a7c6085ac..d1eae6980 100644
--- a/core/client/src/rust/WasmRustCore.ts
+++ b/core/client/src/rust/WasmRustCore.ts
@@ -74,6 +74,7 @@ export function createWasmRustCore(loadWasm: WasmLoader): IRustCore {
symmetricDecryptBytes: (encrypted, keyBase64): Promise<Uint8Array> => ready(() => core.symmetricDecryptBytes(encrypted, keyBase64)),
symmetricEncryptBytes: (plaintext, keyBase64): Promise<Uint8Array> => ready(() => core.symmetricEncryptBytes(plaintext, keyBase64)),
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)),
/*
diff --git a/core/client/src/sharing/SharingService.ts b/core/client/src/sharing/SharingService.ts
index 20f624dcb..ca4e2b347 100644
--- a/core/client/src/sharing/SharingService.ts
+++ b/core/client/src/sharing/SharingService.ts
@@ -2,7 +2,6 @@ import { VaultKeyAlgorithm, type GroupOverviewResponse, type PasswordConfirmatio
import { VaultKeyService } from '../auth/VaultKeyService';
import { StorageKeys } from '../constants/StorageKeys';
-import { EncryptionUtility } from '../crypto/EncryptionUtility';
import { getPlatform } from '../platform/ClientPlatform';
import { devWarn } from '../platform/Logger';
import { rustCore } from '../rust/RustCore';
@@ -25,9 +24,9 @@ export type SharingApi = Pick<WebApiService, 'get' | 'post' | 'delete'>;
export type SrpChallengeResponder = (challenge: PasswordConfirmationChallenge) => Promise<PasswordConfirmationRequest>;
/**
- * Decrypts a vault name encrypted into an invitation for the given public key, or returns null when this session holds no key that opens it.
+ * Decrypts a vault name encrypted into an invitation to the given manifest for the given public key, or returns null when this session holds no key that opens it.
*/
-export type InvitationNameDecryptor = (encryptedName: string, recipientPublicKey: string) => Promise<string | null>;
+export type InvitationNameDecryptor = (encryptedName: string, manifestId: string, recipientPublicKey: string) => Promise<string | null>;
/**
* Service with static helpers implementing the vault sharing flows.
@@ -74,7 +73,7 @@ export class SharingService {
* passes a native call instead, as its private key never leaves the native layer.
* @returns The name of each invitation's vault, keyed by invitation id; invitations whose name will not open are left out.
*/
- public static async openInvitationNames(invitations: ReceivedManifestInvitation[], decryptName: InvitationNameDecryptor = (name, key) => this.decryptWithSessionKey(name, key)): Promise<Record<string, string>> {
+ public static async openInvitationNames(invitations: ReceivedManifestInvitation[], decryptName: InvitationNameDecryptor = (name, manifestId, key) => this.decryptManifestInvitationNameWithSessionKey(name, manifestId, key)): Promise<Record<string, string>> {
const names: Record<string, string> = {};
for (const invitation of invitations) {
@@ -88,7 +87,7 @@ export class SharingService {
}
try {
- const name = await decryptName(invitation.encryptedName, invitation.recipientAccountPublicKey);
+ const name = await decryptName(invitation.encryptedName, invitation.manifestId, invitation.recipientAccountPublicKey);
if (name === null) {
devWarn(`[Sharing] This session holds no account private key that decrypts the name encrypted into invitation ${invitation.id}.`);
continue;
@@ -171,12 +170,13 @@ export class SharingService {
}
/**
- * Decrypt something encrypted for `publicKey` with the account private key of this session.
- * @param ciphertext - the base64 RSA-OAEP ciphertext.
+ * Decrypt an invitation's vault name encrypted for `publicKey` with the account private key of this session.
+ * @param encryptedName - the base64 RSA-OAEP ciphertext.
+ * @param manifestId - the shared manifest the invitation is for.
* @param publicKey - the public half it was encrypted for.
- * @returns The UTF-8 plaintext, or null when this session holds no private key for `publicKey`.
+ * @returns The name, or null when this session holds no private key for `publicKey`.
*/
- private static async decryptWithSessionKey(ciphertext: string, publicKey: string): Promise<string | null> {
+ private static async decryptManifestInvitationNameWithSessionKey(encryptedName: string, manifestId: string, publicKey: string): Promise<string | null> {
if (await VaultKeyService.getAccountPublicKey() !== publicKey) {
return null;
}
@@ -184,7 +184,7 @@ export class SharingService {
if (!privateKey) {
return null;
}
- return new TextDecoder().decode(await EncryptionUtility.decryptWithPrivateKey(ciphertext, privateKey));
+ return rustCore().decryptManifestInvitationName(encryptedName, manifestId, privateKey);
}
}
diff --git a/core/rust/src/bindings/uniffi_api.rs b/core/rust/src/bindings/uniffi_api.rs
index 19e4f034d..3c40f090c 100644
--- a/core/rust/src/bindings/uniffi_api.rs
+++ b/core/rust/src/bindings/uniffi_api.rs
@@ -338,6 +338,12 @@ pub fn rsa_decrypt(base64_ciphertext: String, private_key_jwk: String) -> Result
crate::crypto::decrypt_with_private_key(&base64_ciphertext, &private_key_jwk)
}
+/// Decrypt the shared manifest name encrypted into an invitation for this JWK private key.
+#[uniffi::export]
+pub fn decrypt_manifest_invitation_name(encrypted_name: String, manifest_id: String, private_key_jwk: String) -> Result<String, VaultError> {
+ crate::crypto::decrypt_manifest_invitation_name(&encrypted_name, &manifest_id, &private_key_jwk)
+}
+
/// RSA-OAEP-256 encrypt the Account Key for a mobile login request's JWK public key, as base64.
#[uniffi::export]
pub fn mobile_login_encrypt_account_key(account_key: Vec<u8>, public_key_jwk: String) -> Result<String, VaultError> {
diff --git a/core/rust/src/bindings/wasm.rs b/core/rust/src/bindings/wasm.rs
index ee398a627..b3ca8bb0e 100644
--- a/core/rust/src/bindings/wasm.rs
+++ b/core/rust/src/bindings/wasm.rs
@@ -228,6 +228,12 @@ pub fn rsa_decrypt_js(base64_ciphertext: &str, private_key_jwk: &str) -> Result<
crate::crypto::decrypt_with_private_key(base64_ciphertext, private_key_jwk).map_err(js_err)
}
+/// Decrypt the shared manifest name encrypted into an invitation for this JWK private key.
+#[wasm_bindgen(js_name = decryptManifestInvitationName)]
+pub fn decrypt_manifest_invitation_name_js(encrypted_name: &str, manifest_id: &str, private_key_jwk: &str) -> Result<String, JsValue> {
+ crate::crypto::decrypt_manifest_invitation_name(encrypted_name, manifest_id, 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> {
diff --git a/core/rust/src/crypto/aad.rs b/core/rust/src/crypto/aad.rs
index 1cb457062..4f752c034 100644
--- a/core/rust/src/crypto/aad.rs
+++ b/core/rust/src/crypto/aad.rs
@@ -52,6 +52,11 @@ pub fn grant(manifest_id: &str) -> Vec<u8> {
format!("{}/grant/{}", PREFIX, normalize(manifest_id)).into_bytes()
}
+/// The RSA-OAEP label of a shared manifest's name encrypted into an invitation for its recipient.
+pub fn invitation_name(manifest_id: &str) -> Vec<u8> {
+ format!("{}/invitation-name/{}", PREFIX, normalize(manifest_id)).into_bytes()
+}
+
/// An id as it appears in a label: lowercased, as the server prints a GUID.
pub(crate) fn normalize(id: &str) -> String {
id.to_ascii_lowercase()
@@ -69,6 +74,7 @@ mod tests {
assert_eq!(blob_key("ID", "ABCD"), b"aliasvault/v1/blob-key/id/abcd".to_vec());
assert_eq!(manifest_name("ID"), b"aliasvault/v1/manifest-name/id".to_vec());
assert_eq!(grant("ID"), b"aliasvault/v1/grant/id".to_vec());
+ assert_eq!(invitation_name("ID"), b"aliasvault/v1/invitation-name/id".to_vec());
assert_eq!(MOBILE_LOGIN_ACCOUNT_KEY, b"aliasvault/v1/mobile-login/account-key");
assert_eq!(MOBILE_LOGIN_PAYLOAD_KEY, b"aliasvault/v1/mobile-login/payload-key");
}
diff --git a/core/rust/src/crypto/mod.rs b/core/rust/src/crypto/mod.rs
index c553c5edc..1a353a7e5 100644
--- a/core/rust/src/crypto/mod.rs
+++ b/core/rust/src/crypto/mod.rs
@@ -6,7 +6,7 @@
//! - `jwk`: RSA keys to and from JWK JSON (`rsa`), for the OAEP keys and the RS256 passkey keys.
//! - [`key_chain`]: HKDF-SHA256 (`hkdf`) KEK and SRP input from the unlock key; KEK > Account Key > VEK, private keys.
//! - [`pin`]: PIN unlock: Argon2id + AES-256-GCM wrap of the key the host stores, with the failed-attempt policy.
-//! - [`rsa_oaep`]: RSA-2048 OAEP-SHA256 (`rsa`, blinded decryption); grants and delivery keys.
+//! - [`rsa_oaep`]: RSA-2048 OAEP-SHA256 (`rsa`, blinded decryption); grants, invitation names and delivery keys.
//! - [`signing`]: Ed25519 (`ed25519-dalek`) account signatures over grants, public keys and invitation names.
//! - [`srp`]: SRP-6a client (`srp`, SHA-256, 2048-bit group); login without sending the password.
//! - [`tokens`]: the algorithm, key-type and KDF tokens stored or sent on the wire.
@@ -33,6 +33,6 @@ pub use key_chain::{
reencrypt_account_key, rotate_account_keys, unwrap_account_key, unwrap_key, wrap_key, AccountKeyBlobs, AccountKeyHierarchy, KeyChainError, RotatedAccountKeys, SrpInputError,
};
pub use pin::{pin_decrypt, pin_encrypt, pin_generate_salt, pin_is_locked, pin_register_failure, PinFailure};
-pub use rsa_oaep::{decrypt_with_private_key, decrypt_with_private_key_and_label, encrypt_with_public_key, encrypt_with_public_key_and_label, generate_rsa_key_pair, RsaKeyPair};
+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/rsa_oaep.rs b/core/rust/src/crypto/rsa_oaep.rs
index d1595aa18..d8c6a1d25 100644
--- a/core/rust/src/crypto/rsa_oaep.rs
+++ b/core/rust/src/crypto/rsa_oaep.rs
@@ -45,11 +45,6 @@ pub fn validate_rsa_key_pair(key_pair: &RsaKeyPair) -> VaultResult<()> {
Ok(())
}
-/// Encrypt bytes for the holder of a JWK public key. Returns base64 ciphertext.
-pub fn encrypt_with_public_key(plaintext: &[u8], public_key_jwk: &str) -> VaultResult<String> {
- encrypt(plaintext, public_key_jwk, Oaep::new::<Sha256>())
-}
-
/// Encrypt bytes for the holder of a JWK public key under an OAEP label, which decryption must present as-is.
pub fn encrypt_with_public_key_and_label(plaintext: &[u8], public_key_jwk: &str, label: &[u8]) -> VaultResult<String> {
encrypt(plaintext, public_key_jwk, Oaep::new_with_label::<Sha256, _>(label_text(label)?))
@@ -65,6 +60,12 @@ pub fn decrypt_with_private_key_and_label(base64_ciphertext: &str, private_key_j
decrypt(base64_ciphertext, private_key_jwk, Oaep::new_with_label::<Sha256, _>(label_text(label)?))
}
+/// Decrypt the shared manifest name encrypted into an invitation for this JWK private key, as UTF-8 text.
+pub fn decrypt_manifest_invitation_name(encrypted_name: &str, manifest_id: &str, private_key_jwk: &str) -> VaultResult<String> {
+ let plaintext = decrypt_with_private_key_and_label(encrypted_name, private_key_jwk, &super::aad::invitation_name(manifest_id))?;
+ String::from_utf8(plaintext).map_err(|_| VaultError::General("Decrypted invitation name is not valid text".to_string()))
+}
+
fn encrypt(plaintext: &[u8], public_key_jwk: &str, padding: Oaep) -> VaultResult<String> {
let public = rsa_public_from_jwk(public_key_jwk)?;
let ciphertext = public.encrypt(&mut rand_core06::OsRng, padding, plaintext).map_err(|e| VaultError::General(format!("RSA-OAEP encryption failed: {}", e)))?;
@@ -98,4 +99,12 @@ mod tests {
assert!(decrypt_with_private_key_and_label(&ciphertext, &pair.private_key, b"grant/b").is_err());
assert!(decrypt_with_private_key(&ciphertext, &pair.private_key).is_err(), "a labelled ciphertext does not open without its label");
}
+
+ #[test]
+ fn manifest_invitation_name_is_bound_to_its_manifest() {
+ let pair = generate_rsa_key_pair().unwrap();
+ let ciphertext = encrypt_with_public_key_and_label("Family".as_bytes(), &pair.public_key, &super::super::aad::invitation_name("A")).unwrap();
+ assert_eq!(decrypt_manifest_invitation_name(&ciphertext, "a", &pair.private_key).unwrap(), "Family");
+ assert!(decrypt_manifest_invitation_name(&ciphertext, "b", &pair.private_key).is_err());
+ }
}
diff --git a/core/rust/src/vault_sync/sharing.rs b/core/rust/src/vault_sync/sharing.rs
index 483226de0..56394df44 100644
--- a/core/rust/src/vault_sync/sharing.rs
+++ b/core/rust/src/vault_sync/sharing.rs
@@ -603,7 +603,7 @@ async fn invite_to_shared_manifest(ctx: &mut Ctx) -> Outcome {
}
.filter(|name| !name.is_empty() && name.len() <= MAX_SHARED_MANIFEST_NAME_BYTES);
let encrypted_vek = keys::encrypt_manifest_vek(manifest_vek.expose_secret(), &manifest.manifest_id, &recipient_public_key)?;
- let encrypted_name = name.map(|name| crypto::encrypt_with_public_key(name.as_bytes(), &recipient_public_key)).transpose()?;
+ let encrypted_name = name.map(|name| crypto::encrypt_with_public_key_and_label(name.as_bytes(), &recipient_public_key, &crypto::aad::invitation_name(&manifest.manifest_id))).transpose()?;
let grant = ManifestGrant {
recipient_user_id: recipient.user_id.clone(),
recipient_account_public_key_id: recipient_public_key_id,