Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Move mobile login encryption call to Rust core (#2469)
Leendert de Borst0817a44f1bca
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultCrypto.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultCrypto.ktindex 9d05476fc..aefbdb385 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultCrypto.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultCrypto.kt@@ -8,11 +8,11 @@ import net.aliasvault.app.vaultstore.keystoreprovider.KeystoreProviderimport net.aliasvault.app.vaultstore.storageprovider.StorageProviderimport org.json.JSONObjectimport uniffi.aliasvault_core.KeyChainException-import java.math.BigIntegerimport java.security.SecureRandomimport javax.crypto.Cipherimport javax.crypto.spec.GCMParameterSpecimport javax.crypto.spec.SecretKeySpec+import uniffi.aliasvault_core.mobileLoginEncryptAccountKey as rustMobileLoginEncryptAccountKeyimport uniffi.aliasvault_core.openAccountKeyChain as rustOpenAccountKeyChain/**@@ -439,7 +439,7 @@ class VaultCrypto(override fun onSuccess(key: String) {try {val keyBytes = Base64.decode(key, Base64.NO_WRAP)- result = encryptWithPublicKey(keyBytes, publicKeyJWK)+ result = rustMobileLoginEncryptAccountKey(keyBytes, publicKeyJWK)} catch (e: Exception) {error = eLog.e(TAG, "Error encrypting key for mobile login", e)@@ -462,24 +462,5 @@ class VaultCrypto(return result ?: throw Exception("Failed to encrypt key for mobile login")}- private fun encryptWithPublicKey(data: ByteArray, publicKeyJWK: String): String {- val jwk = JSONObject(publicKeyJWK)- val nStr = jwk.getString("n")- val eStr = jwk.getString("e")-- val modulus = BigInteger(1, Base64.decode(nStr, Base64.URL_SAFE or Base64.NO_PADDING or Base64.NO_WRAP))- val exponent = BigInteger(1, Base64.decode(eStr, Base64.URL_SAFE or Base64.NO_PADDING or Base64.NO_WRAP))-- val keySpec = java.security.spec.RSAPublicKeySpec(modulus, exponent)- val keyFactory = java.security.KeyFactory.getInstance("RSA")- val publicKey = keyFactory.generatePublic(keySpec)-- val cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding")- cipher.init(Cipher.ENCRYPT_MODE, publicKey)-- val encryptedBytes = cipher.doFinal(data)- return Base64.encodeToString(encryptedBytes, Base64.NO_WRAP)- }-// endregion}diff --git a/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift b/apps/mobile-app/ios/NativeVaultManager/VaultManager.swiftindex c3e40e912..132e5b05f 100644--- a/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift+++ b/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift@@ -1145,12 +1145,7 @@ public class VaultManager: NSObject {resolver resolve: @escaping RCTPromiseResolveBlock,rejecter reject: @escaping RCTPromiseRejectBlock) {do {- // Encrypt the Account Key with the provided public key- let encryptedData = try vaultStore.encryptAccountKeyForMobileLogin(publicKeyJWK: publicKeyJWK)-- // Return the encrypted data as base64 string- let base64Encrypted = encryptedData.base64EncodedString()- resolve(base64Encrypted)+ resolve(try vaultStore.encryptAccountKeyForMobileLogin(publicKeyJWK: publicKeyJWK))} catch {reject("ENCRYPTION_ERROR", "Failed to encrypt decryption key: \(error.localizedDescription)", error)}diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+PublicKeyCrypto.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+PublicKeyCrypto.swiftindex 6b651bc0a..3a1ccecad 100644--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+PublicKeyCrypto.swift+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+PublicKeyCrypto.swift@@ -1,185 +1,12 @@import Foundation-import Security+import RustCoreFramework/// Extension for the VaultStore class to handle RSA public key encryptionextension VaultStore {- /// Encrypts the Account Key using an RSA public key for mobile login- /// The receiving client opens the account key chain with it.- /// - Parameter publicKeyJWK: The RSA public key in JWK format (JSON string)- /// - Returns: The encrypted Account Key- public func encryptAccountKeyForMobileLogin(publicKeyJWK: String) throws -> Data {- // Only works while the vault is unlocked (Account Key in memory)+ /// Encrypts the Account Key with a mobile login request's RSA public key (JWK JSON) for the receiving client, as base64.+ /// Only works while the vault is unlocked (Account Key in memory).+ public func encryptAccountKeyForMobileLogin(publicKeyJWK: String) throws -> String {let accountKey = try getAccountKey()- return try encryptWithPublicKey(data: accountKey, publicKeyJWK: publicKeyJWK)- }-- /// Encrypts data using an RSA public key- /// - Parameters:- /// - data: The data to encrypt- /// - publicKeyBase64: The RSA public key in JWK format (JSON string, base64 encoded after conversion)- /// - Returns: The encrypted data- internal func encryptWithPublicKey(data: Data, publicKeyJWK: String) throws -> Data {- // Parse the JWK JSON- guard let jwkData = publicKeyJWK.data(using: .utf8),- let jwk = try? JSONSerialization.jsonObject(with: jwkData) as? [String: Any],- let modulusB64 = jwk["n"] as? String,- let exponentB64 = jwk["e"] as? String else {- throw NSError(domain: "VaultStore", code: 100, userInfo: [NSLocalizedDescriptionKey: "Invalid JWK format"])- }-- // Decode modulus and exponent from base64url- guard let modulusData = base64UrlDecode(modulusB64),- let exponentData = base64UrlDecode(exponentB64) else {- throw NSError(domain: "VaultStore", code: 101, userInfo: [NSLocalizedDescriptionKey: "Failed to decode JWK components"])- }-- // Create RSA public key- let publicKey = try createPublicKey(modulus: modulusData, exponent: exponentData)-- // Encrypt the data using RSA-OAEP with SHA-256- var error: Unmanaged<CFError>?- guard let encryptedData = SecKeyCreateEncryptedData(- publicKey,- .rsaEncryptionOAEPSHA256,- data as CFData,- &error- ) as Data? else {- let errorDescription = error?.takeRetainedValue().localizedDescription ?? "Unknown error"- throw NSError(domain: "VaultStore", code: 102, userInfo: [NSLocalizedDescriptionKey: "RSA encryption failed: \(errorDescription)"])- }-- return encryptedData- }-- /// Creates an RSA public key from modulus and exponent- private func createPublicKey(modulus: Data, exponent: Data) throws -> SecKey {- // Create the key attributes- let keyDict: [String: Any] = [- kSecAttrKeyType as String: kSecAttrKeyTypeRSA,- kSecAttrKeyClass as String: kSecAttrKeyClassPublic,- kSecAttrKeySizeInBits as String: modulus.count * 8- ]-- // Create the public key data in ASN.1 format- let publicKeyData = createPublicKeyASN1(modulus: modulus, exponent: exponent)-- var error: Unmanaged<CFError>?- guard let publicKey = SecKeyCreateWithData(- publicKeyData as CFData,- keyDict as CFDictionary,- &error- ) else {- let errorDescription = error?.takeRetainedValue().localizedDescription ?? "Unknown error"- throw NSError(domain: "VaultStore", code: 103, userInfo: [NSLocalizedDescriptionKey: "Failed to create public key: \(errorDescription)"])- }-- return publicKey- }-- /// Creates ASN.1 DER encoded public key data from modulus and exponent- private func createPublicKeyASN1(modulus: Data, exponent: Data) -> Data {- // RSA Public Key ASN.1 structure:- // SEQUENCE {- // SEQUENCE {- // OBJECT IDENTIFIER rsaEncryption- // NULL- // }- // BIT STRING {- // SEQUENCE {- // INTEGER modulus- // INTEGER exponent- // }- // }- // }-- var result = Data()-- // Inner sequence: modulus and exponent- let modulusEncoded = encodeASN1Integer(modulus)- let exponentEncoded = encodeASN1Integer(exponent)- let innerSequence = encodeASN1Sequence(modulusEncoded + exponentEncoded)-- // Bit string containing the inner sequence- let bitString = encodeASN1BitString(innerSequence)-- // Algorithm identifier sequence- let algorithmOID = Data([0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01]) // rsaEncryption OID- let algorithmNull = Data([0x05, 0x00])- let algorithmSequence = encodeASN1Sequence(algorithmOID + algorithmNull)-- // Outer sequence- result = encodeASN1Sequence(algorithmSequence + bitString)-- return result- }-- /// Encodes data as ASN.1 SEQUENCE- private func encodeASN1Sequence(_ data: Data) -> Data {- return encodeASN1(tag: 0x30, data: data)- }-- /// Encodes data as ASN.1 INTEGER- private func encodeASN1Integer(_ data: Data) -> Data {- var integerData = data-- // Remove leading zeros- while integerData.count > 1 && integerData[0] == 0 {- integerData = integerData.dropFirst()- }-- // Add padding byte if the high bit is set (to keep it positive)- if let firstByte = integerData.first, firstByte >= 0x80 {- integerData.insert(0x00, at: 0)- }-- return encodeASN1(tag: 0x02, data: integerData)- }-- /// Encodes data as ASN.1 BIT STRING- private func encodeASN1BitString(_ data: Data) -> Data {- var bitStringData = Data([0x00]) // No unused bits- bitStringData.append(data)- return encodeASN1(tag: 0x03, data: bitStringData)- }-- /// Encodes data with ASN.1 tag and length- private func encodeASN1(tag: UInt8, data: Data) -> Data {- var result = Data([tag])- result.append(encodeASN1Length(data.count))- result.append(data)- return result- }-- /// Encodes length in ASN.1 format- private func encodeASN1Length(_ length: Int) -> Data {- if length < 128 {- return Data([UInt8(length)])- }-- var lengthBytes = Data()- var len = length- while len > 0 {- lengthBytes.insert(UInt8(len & 0xFF), at: 0)- len >>= 8- }-- var result = Data([UInt8(0x80 | lengthBytes.count)])- result.append(lengthBytes)- return result- }-- /// Decodes base64url string to Data- private func base64UrlDecode(_ base64url: String) -> Data? {- var base64 = base64url- .replacingOccurrences(of: "-", with: "+")- .replacingOccurrences(of: "_", with: "/")-- // Add padding if needed- let remainder = base64.count % 4- if remainder > 0 {- base64 += String(repeating: "=", count: 4 - remainder)- }-- return Data(base64Encoded: base64)+ return try RustCoreFramework.mobileLoginEncryptAccountKey(accountKey: accountKey, publicKeyJwk: publicKeyJWK)}}diff --git a/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs b/apps/server/AliasVault.Api/Controllers/V2/AuthController.csindex 17cf64b9a..94fbd3426 100644--- a/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs+++ b/apps/server/AliasVault.Api/Controllers/V2/AuthController.cs@@ -976,7 +976,7 @@ public class AuthController(IAliasServerDbContextFactory dbContextFactory, UserM// The payload is encrypted with a one-off symmetric key, which in turn is encrypted with the client's RSA public key.var symmetricKey = Cryptography.Encryption.GenerateRandomSymmetricKey();var encryptedPayload = Cryptography.Encryption.SymmetricEncrypt(JsonSerializer.Serialize(payload, MobileLoginRequestHelper.PayloadJsonOptions), symmetricKey);- var encryptedSymmetricKey = Cryptography.Encryption.EncryptSymmetricKeyWithRsa(symmetricKey, clientPublicKey);+ var encryptedSymmetricKey = Cryptography.Encryption.EncryptSymmetricKeyWithRsa(symmetricKey, clientPublicKey, Cryptography.Encryption.MobileLoginPayloadKeyLabel);await authLoggingService.LogAuthEventSuccessAsync(user.UserName!, AuthEventType.MobileLogin);diff --git a/apps/server/Utilities/AliasVault.Cryptography/Encryption.cs b/apps/server/Utilities/AliasVault.Cryptography/Encryption.csindex 50b6a23f7..59f94e54d 100644--- a/apps/server/Utilities/AliasVault.Cryptography/Encryption.cs+++ b/apps/server/Utilities/AliasVault.Cryptography/Encryption.cs@@ -10,12 +10,23 @@ namespace AliasVault.Cryptography;using System.Security.Cryptography;using System.Text;using System.Text.Json;+using Org.BouncyCastle.Crypto.Digests;+using Org.BouncyCastle.Crypto.Encodings;+using Org.BouncyCastle.Crypto.Engines;+using Org.BouncyCastle.Crypto.Parameters;+using Org.BouncyCastle.Security;/// <summary>/// RSA/AES and Argon2id encryption methods./// </summary>public static class Encryption{+ /// <summary>+ /// The RSA-OAEP label of the session payload key the server encrypts for a mobile login request's one-off public key.+ /// Must match <c>MOBILE_LOGIN_PAYLOAD_KEY</c> in <c>core/rust/src/crypto/aad.rs</c>.+ /// </summary>+ public const string MobileLoginPayloadKeyLabel = "aliasvault/v1/mobile-login/payload-key";+/// <summary>/// Generates a random symmetric key for use with AES-256./// </summary>@@ -60,6 +71,39 @@ public static class Encryptionreturn rsa.Decrypt(cipherBytes, rsaParams);}+ /// <summary>+ /// Encrypts a symmetric key using an RSA public key under an OAEP label, which decryption must present as-is.+ /// </summary>+ /// <param name="symmetricKey">The symmetric key to encrypt.</param>+ /// <param name="publicKey">The RSA public key in JWK format.</param>+ /// <param name="label">The OAEP label.</param>+ /// <returns>The encrypted symmetric key as a base64-encoded string.</returns>+ public static string EncryptSymmetricKeyWithRsa(byte[] symmetricKey, string publicKey, string label)+ {+ var jwk = JsonSerializer.Deserialize<JsonElement>(publicKey);+ var key = new RsaKeyParameters(false, JwkInteger(jwk, "n"), JwkInteger(jwk, "e"));+ var oaep = LabelledOaep(label);+ oaep.Init(true, new ParametersWithRandom(key, new SecureRandom()));+ return Convert.ToBase64String(oaep.ProcessBlock(symmetricKey, 0, symmetricKey.Length));+ }++ /// <summary>+ /// Decrypts a symmetric key that was encrypted with an RSA public key under an OAEP label.+ /// </summary>+ /// <param name="ciphertext">The encrypted symmetric key as base64.</param>+ /// <param name="privateKey">The RSA private key in JWK format.</param>+ /// <param name="label">The OAEP label the ciphertext was encrypted under.</param>+ /// <returns>The decrypted symmetric key.</returns>+ public static byte[] DecryptSymmetricKeyWithRsa(string ciphertext, string privateKey, string label)+ {+ var jwk = JsonSerializer.Deserialize<JsonElement>(privateKey);+ var key = new RsaPrivateCrtKeyParameters(JwkInteger(jwk, "n"), JwkInteger(jwk, "e"), JwkInteger(jwk, "d"), JwkInteger(jwk, "p"), JwkInteger(jwk, "q"), JwkInteger(jwk, "dp"), JwkInteger(jwk, "dq"), JwkInteger(jwk, "qi"));+ var oaep = LabelledOaep(label);+ oaep.Init(false, new ParametersWithRandom(key, new SecureRandom()));+ var cipherBytes = Convert.FromBase64String(ciphertext);+ return oaep.ProcessBlock(cipherBytes, 0, cipherBytes.Length);+ }+/// <summary>/// SymmetricEncrypt a plaintext string using AES-256 GCM./// </summary>@@ -137,6 +181,27 @@ public static class Encryptionreturn plaintext;}+ /// <summary>+ /// RSA-OAEP with SHA-256 for both the hash and MGF1, as WebCrypto's RSA-OAEP-256, under the given label.+ /// </summary>+ /// <param name="label">The OAEP label.</param>+ /// <returns>The OAEP encoding, not yet initialized.</returns>+ private static OaepEncoding LabelledOaep(string label)+ {+ return new OaepEncoding(new RsaBlindedEngine(), new Sha256Digest(), new Sha256Digest(), Encoding.UTF8.GetBytes(label));+ }++ /// <summary>+ /// Reads an unsigned big-endian JWK integer member.+ /// </summary>+ /// <param name="jwk">The parsed JWK.</param>+ /// <param name="name">The member name.</param>+ /// <returns>The integer.</returns>+ private static Org.BouncyCastle.Math.BigInteger JwkInteger(JsonElement jwk, string name)+ {+ return new Org.BouncyCastle.Math.BigInteger(1, Base64UrlDecode(jwk.GetProperty(name).GetString()!));+ }+/// <summary>/// Imports a public key from JWK format into an RSA provider./// </summary>diff --git a/core/client/src/auth/MobileLoginProtocol.ts b/core/client/src/auth/MobileLoginProtocol.tsindex cbbdb1ce1..d87240a59 100644--- a/core/client/src/auth/MobileLoginProtocol.ts+++ b/core/client/src/auth/MobileLoginProtocol.ts@@ -17,6 +17,12 @@ export class MobileLoginProtocol {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 VERIFICATION_CODE_CONTEXT = 'AliasVault.MobileLogin.VerificationCode.v1:';private static readonly REQUEST_ID_PATTERN = /^[0-9a-f]{32}$/;diff --git a/core/client/src/auth/MobileLoginService.ts b/core/client/src/auth/MobileLoginService.tsindex 9196bb6da..3841f9714 100644--- a/core/client/src/auth/MobileLoginService.ts+++ b/core/client/src/auth/MobileLoginService.ts@@ -154,10 +154,10 @@ export class MobileLoginService {this.cleanup();// The mobile app encrypted its stored key with our public key.- const unlockKey = bytesToBase64(await EncryptionUtility.decryptWithPrivateKeyObject(data.encryptedAccountKey, privateKey));+ const unlockKey = 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));+ const symmetricKey = bytesToBase64(await EncryptionUtility.decryptWithPrivateKeyObject(data.encryptedSymmetricKey, privateKey, MobileLoginProtocol.PAYLOAD_KEY_LABEL));const payload = JSON.parse(await EncryptionUtility.symmetricDecrypt(data.encryptedPayload, symmetricKey)) as MobileLoginPayload;onSuccess({diff --git a/core/client/src/crypto/EncryptionUtility.ts b/core/client/src/crypto/EncryptionUtility.tsindex 051206485..27334ee93 100644--- a/core/client/src/crypto/EncryptionUtility.ts+++ b/core/client/src/crypto/EncryptionUtility.ts@@ -242,14 +242,12 @@ export class EncryptionUtility {}/**- * Decrypts data using RSA-OAEP asymmetric encryption with a CryptoKey private key.+ * 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): Promise<Uint8Array> {+ public static async decryptWithPrivateKeyObject(ciphertext: string, privateKey: CryptoKey, label?: string): Promise<Uint8Array> {const cipherBuffer = base64ToBytes(ciphertext);const plaintextBuffer = await crypto.subtle.decrypt(- {- name: "RSA-OAEP",- },+ label === undefined ? { name: "RSA-OAEP" } : { name: "RSA-OAEP", label: new TextEncoder().encode(label) },privateKey,cipherBuffer);diff --git a/core/rust/src/bindings/uniffi_api.rs b/core/rust/src/bindings/uniffi_api.rsindex a465b6ed3..6f211ea95 100644--- a/core/rust/src/bindings/uniffi_api.rs+++ b/core/rust/src/bindings/uniffi_api.rs@@ -322,6 +322,12 @@ pub fn rsa_decrypt(base64_ciphertext: String, private_key_jwk: String) -> Resultcrate::crypto::decrypt_with_private_key(&base64_ciphertext, &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> {+ crate::crypto::encrypt_with_public_key_and_label(&account_key, &public_key_jwk, crate::crypto::aad::MOBILE_LOGIN_ACCOUNT_KEY)+}+// ═══════════════════════════════════════════════════════════════════════════════// Vault sync engine// ═══════════════════════════════════════════════════════════════════════════════diff --git a/core/rust/src/crypto/aad.rs b/core/rust/src/crypto/aad.rsindex 06fef44ec..0f1a113d4 100644--- a/core/rust/src/crypto/aad.rs+++ b/core/rust/src/crypto/aad.rs@@ -15,6 +15,12 @@ pub const ACCOUNT_PRIVATE_KEY: &[u8] = b"aliasvault/v1/account-private-key";/// The account Ed25519 signing private key under the Account Key.pub const ACCOUNT_SIGNING_PRIVATE_KEY: &[u8] = b"aliasvault/v1/account-signing-private-key";+/// The RSA-OAEP label of the Account Key a mobile app encrypts for a mobile login request's one-off public key.+pub const MOBILE_LOGIN_ACCOUNT_KEY: &[u8] = b"aliasvault/v1/mobile-login/account-key";++/// The RSA-OAEP label of the session payload key the server encrypts for a mobile login request's one-off public key.+pub const MOBILE_LOGIN_PAYLOAD_KEY: &[u8] = b"aliasvault/v1/mobile-login/payload-key";+/// A manifest payload under its manifest's VEK.pub fn manifest(manifest_id: &str) -> Vec<u8> {format!("{}/manifest/{}", PREFIX, normalize(manifest_id)).into_bytes()@@ -62,5 +68,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!(MOBILE_LOGIN_ACCOUNT_KEY, b"aliasvault/v1/mobile-login/account-key");+ assert_eq!(MOBILE_LOGIN_PAYLOAD_KEY, b"aliasvault/v1/mobile-login/payload-key");}}