Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Replace Argon2id .NET with Rust implementation (#2159)
Leendert de Borst7b80e580aa48
diff --git a/apps/server/AliasVault.Client/Auth/Pages/Login.razor b/apps/server/AliasVault.Client/Auth/Pages/Login.razorindex b0c5c33ec..1913de9eb 100644--- a/apps/server/AliasVault.Client/Auth/Pages/Login.razor+++ b/apps/server/AliasVault.Client/Auth/Pages/Login.razor@@ -269,7 +269,7 @@ elsevar srpIdentity = loginResponse.SrpIdentity ?? username;// 3. Client derives shared session key.- _passwordHash = await Encryption.DeriveKeyFromPasswordAsync(_loginModel.Password, loginResponse.Salt, loginResponse.EncryptionType, loginResponse.EncryptionSettings);+ _passwordHash = await RustCoreService.Argon2DeriveKeyAsync(_loginModel.Password, loginResponse.Salt, loginResponse.EncryptionSettings);var passwordHashString = BitConverter.ToString(_passwordHash).Replace("-", string.Empty);_clientEphemeral = await RustCoreService.SrpGenerateEphemeralAsync();diff --git a/apps/server/AliasVault.Client/Auth/Pages/Unlock.razor b/apps/server/AliasVault.Client/Auth/Pages/Unlock.razorindex e332d6178..34e15a576 100644--- a/apps/server/AliasVault.Client/Auth/Pages/Unlock.razor+++ b/apps/server/AliasVault.Client/Auth/Pages/Unlock.razor@@ -3,11 +3,13 @@@inherits AliasVault.Client.Auth.Pages.Base.LoginBase@inject ILogger<Unlock> Logger@inject IJSRuntime JSRuntime+@inject RustCoreService RustCoreService@layout Auth.Layout.MainLayout@using System.Text.Json@using AliasVault.Client.Auth.Components@using AliasVault.Client.Auth.Models@using AliasVault.Client.Services+@using AliasVault.Client.Services.JsInterop.RustCore@using AliasVault.Client.Utilities@using AliasVault.Shared.Models.WebApi.V1.Auth@using AliasVault.Cryptography.Client@@ -187,7 +189,7 @@ else}// 3. Client derives shared session key.- byte[] passwordHash = await Encryption.DeriveKeyFromPasswordAsync(_unlockModel.Password, loginResponse.Salt, loginResponse.EncryptionType, loginResponse.EncryptionSettings);+ byte[] passwordHash = await RustCoreService.Argon2DeriveKeyAsync(_unlockModel.Password, loginResponse.Salt, loginResponse.EncryptionSettings);// Check if the password is correct locally by decrypting the test string.var validPassword = await AuthService.ValidateEncryptionKeyAsync(passwordHash);diff --git a/apps/server/AliasVault.Client/Main/Pages/Settings/Security/ChangePassword.razor b/apps/server/AliasVault.Client/Main/Pages/Settings/Security/ChangePassword.razorindex d8223e234..99d00888a 100644--- a/apps/server/AliasVault.Client/Main/Pages/Settings/Security/ChangePassword.razor+++ b/apps/server/AliasVault.Client/Main/Pages/Settings/Security/ChangePassword.razor@@ -103,11 +103,6 @@ else/// </summary>private string CurrentServerEphemeral { get; set; } = string.Empty;- /// <summary>- /// Gets or sets the current user's password encryption type.- /// </summary>- private string CurrentEncryptionType { get; set; } = string.Empty;-/// <summary>/// Gets or sets the current user's password encryption settings./// </summary>@@ -299,7 +294,6 @@ elseCurrentServerEphemeral = response.ServerEphemeral;CurrentSalt = response.Salt;- CurrentEncryptionType = response.EncryptionType;CurrentEncryptionSettings = response.EncryptionSettings;CurrentSrpIdentity = response.SrpIdentity;}@@ -334,7 +328,7 @@ elseStateHasChanged();// Generate ephemeral for current password to verify it.- var currentPasswordHash = await Encryption.DeriveKeyFromPasswordAsync(PasswordChangeFormModel.CurrentPassword, CurrentSalt, CurrentEncryptionType, CurrentEncryptionSettings);+ var currentPasswordHash = await RustCoreService.Argon2DeriveKeyAsync(PasswordChangeFormModel.CurrentPassword, CurrentSalt, CurrentEncryptionSettings);var currentPasswordHashString = BitConverter.ToString(currentPasswordHash).Replace("-", string.Empty);ClientEphemeral = await RustCoreService.SrpGenerateEphemeralAsync();@@ -358,7 +352,7 @@ else// was derived with a different salt.var newSalt = await RustCoreService.SrpGenerateSaltAsync();- byte[] newPasswordHash = await Encryption.DeriveKeyFromPasswordAsync(PasswordChangeFormModel.NewPassword, newSalt);+ byte[] newPasswordHash = await RustCoreService.Argon2DeriveKeyAsync(PasswordChangeFormModel.NewPassword, newSalt);var newPasswordHashString = BitConverter.ToString(newPasswordHash).Replace("-", string.Empty);// Backup current password hash in case of failure.diff --git a/apps/server/AliasVault.Client/Main/Pages/Settings/Security/DeleteAccount.razor b/apps/server/AliasVault.Client/Main/Pages/Settings/Security/DeleteAccount.razorindex 9254a1040..cac82cd2b 100644--- a/apps/server/AliasVault.Client/Main/Pages/Settings/Security/DeleteAccount.razor+++ b/apps/server/AliasVault.Client/Main/Pages/Settings/Security/DeleteAccount.razor@@ -182,7 +182,7 @@var srpIdentity = loginResponse.SrpIdentity ?? username;// Verify password using SRP- var passwordHash = await Encryption.DeriveKeyFromPasswordAsync(_passwordModel.Password, loginResponse.Salt, loginResponse.EncryptionType, loginResponse.EncryptionSettings);+ var passwordHash = await RustCoreService.Argon2DeriveKeyAsync(_passwordModel.Password, loginResponse.Salt, loginResponse.EncryptionSettings);var passwordHashString = BitConverter.ToString(passwordHash).Replace("-", string.Empty);ClientEphemeral = await RustCoreService.SrpGenerateEphemeralAsync();diff --git a/apps/server/AliasVault.Client/Services/Auth/AuthService.cs b/apps/server/AliasVault.Client/Services/Auth/AuthService.csindex 205e60417..6d8b00857 100644--- a/apps/server/AliasVault.Client/Services/Auth/AuthService.cs+++ b/apps/server/AliasVault.Client/Services/Auth/AuthService.cs@@ -10,7 +10,7 @@ namespace AliasVault.Client.Services.Auth;using System.Net.Http.Json;using System.Text.Json;using AliasVault.Client.Services.Auth.Enums;-using AliasVault.Cryptography.Client;+using AliasVault.Client.Services.JsInterop.RustCore;using AliasVault.Shared.Models.WebApi.V1.Auth;using Blazored.LocalStorage;using Microsoft.AspNetCore.Components.WebAssembly.Hosting;@@ -24,7 +24,8 @@ using Microsoft.AspNetCore.Components.WebAssembly.Hosting;/// <param name="environment">IWebAssemblyHostEnvironment instance.</param>/// <param name="config">Config instance.</param>/// <param name="jsInteropService">JSInteropService instance.</param>-public sealed class AuthService(HttpClient httpClient, ILocalStorageService localStorage, IWebAssemblyHostEnvironment environment, Config config, JsInteropService jsInteropService)+/// <param name="rustCoreService">RustCoreService instance.</param>+public sealed class AuthService(HttpClient httpClient, ILocalStorageService localStorage, IWebAssemblyHostEnvironment environment, Config config, JsInteropService jsInteropService, RustCoreService rustCoreService){/// <summary>/// Test string value that is stored in local storage in encrypted state. This is used to validate the encryption key@@ -312,11 +313,7 @@ public sealed class AuthService(HttpClient httpClient, ILocalStorageService loca}// Derive password hash using server parameters- byte[] passwordHash = await Encryption.DeriveKeyFromPasswordAsync(- password,- loginResponse.Salt,- loginResponse.EncryptionType,- loginResponse.EncryptionSettings);+ byte[] passwordHash = await rustCoreService.Argon2DeriveKeyAsync(password, loginResponse.Salt, loginResponse.EncryptionSettings);// Verify the password locally using the derived password hashvar isValidPassword = await ValidateEncryptionKeyAsync(passwordHash);diff --git a/apps/server/AliasVault.Client/Services/Auth/UserRegistrationService.cs b/apps/server/AliasVault.Client/Services/Auth/UserRegistrationService.csindex 84a79d4ec..aea0ddb0d 100644--- a/apps/server/AliasVault.Client/Services/Auth/UserRegistrationService.cs+++ b/apps/server/AliasVault.Client/Services/Auth/UserRegistrationService.cs@@ -54,7 +54,7 @@ public class UserRegistrationService(HttpClient httpClient, AuthenticationStateP// Generate salt using Rust WASMvar salt = await rustCoreService.SrpGenerateSaltAsync();- var passwordHash = await Encryption.DeriveKeyFromPasswordAsync(password, salt, encryptionType, encryptionSettings);+ var passwordHash = await rustCoreService.Argon2DeriveKeyAsync(password, salt, encryptionSettings);var passwordHashString = BitConverter.ToString(passwordHash).Replace("-", string.Empty);// Derive SRP private key and verifier using the same saltdiff --git a/apps/server/AliasVault.Client/Services/Crypto/AvexCryptoService.cs b/apps/server/AliasVault.Client/Services/Crypto/AvexCryptoService.csindex d263461f8..e29fbcabc 100644--- a/apps/server/AliasVault.Client/Services/Crypto/AvexCryptoService.cs+++ b/apps/server/AliasVault.Client/Services/Crypto/AvexCryptoService.cs@@ -10,6 +10,7 @@ namespace AliasVault.Client.Services.Crypto;using System.Text;using System.Text.Json;using AliasVault.Client.Services.JsInterop;+using AliasVault.Client.Services.JsInterop.RustCore;using AliasVault.ImportExport.Constants;using AliasVault.ImportExport.Models.Exports;using AliasVault.Shared.Core;@@ -21,14 +22,17 @@ using AliasVault.Shared.Core;public class AvexCryptoService{private readonly JsInteropService jsInteropService;+ private readonly RustCoreService rustCoreService;/// <summary>/// Initializes a new instance of the <see cref="AvexCryptoService"/> class./// </summary>/// <param name="jsInteropService">The JS interop service.</param>- public AvexCryptoService(JsInteropService jsInteropService)+ /// <param name="rustCoreService">The Rust core service.</param>+ public AvexCryptoService(JsInteropService jsInteropService, RustCoreService rustCoreService){this.jsInteropService = jsInteropService;+ this.rustCoreService = rustCoreService;}/// <summary>@@ -46,11 +50,7 @@ public class AvexCryptoService// 2. Derive key using Argon2id (same as existing vault encryption)var saltBase64 = Convert.ToBase64String(salt);- var key = await AliasVault.Cryptography.Client.Encryption.DeriveKeyFromPasswordAsync(- exportPassword,- saltBase64,- AliasVault.Cryptography.Client.Defaults.EncryptionType,- AliasVault.Cryptography.Client.Defaults.EncryptionSettings);+ var key = await this.rustCoreService.Argon2DeriveKeyAsync(exportPassword, saltBase64, AliasVault.Cryptography.Client.Defaults.EncryptionSettings);// 3. Encrypt the .avux bytes using AES-256-GCM via JavaScriptvar encryptedPayload = await this.jsInteropService.SymmetricEncryptBytes(avuxBytes, key);@@ -133,18 +133,16 @@ public class AvexCryptoServicevar encryptedPayload = new byte[encryptedPayloadLength];Buffer.BlockCopy(avexBytes, (int)payloadOffset, encryptedPayload, 0, encryptedPayloadLength);- // 4. Derive key using Argon2id (C# library works in Blazor WASM)- if (header.Kdf.Type != "Argon2Id" && header.Kdf.Type != "Argon2id")+ /*+ * 4. Derive key using Argon2id via the Rust core.+ */+ if (header.Kdf.Type.ToLowerInvariant() != "argon2id"){throw new InvalidOperationException($"Unsupported KDF type: {header.Kdf.Type}. Only Argon2id is supported.");}var kdfSettings = JsonSerializer.Serialize(header.Kdf.Params);- var key = await AliasVault.Cryptography.Client.Encryption.DeriveKeyFromPasswordAsync(- exportPassword,- header.Kdf.Salt,- header.Kdf.Type,- kdfSettings);+ var key = await this.rustCoreService.Argon2DeriveKeyAsync(exportPassword, header.Kdf.Salt, kdfSettings);// 5. Decrypt payloadbyte[] avuxBytes;diff --git a/apps/server/AliasVault.Client/Services/JsInterop/RustCore/RustCoreService.cs b/apps/server/AliasVault.Client/Services/JsInterop/RustCore/RustCoreService.csindex 708b7b188..d096da897 100644--- a/apps/server/AliasVault.Client/Services/JsInterop/RustCore/RustCoreService.cs+++ b/apps/server/AliasVault.Client/Services/JsInterop/RustCore/RustCoreService.cs@@ -228,6 +228,24 @@ public class RustCoreService : IAsyncDisposable}}+ /// <summary>+ /// Derive a key from a password using Argon2id.+ /// </summary>+ /// <param name="password">The password, hashed as its UTF-8 bytes.</param>+ /// <param name="salt">The salt, hashed as its UTF-8 bytes.</param>+ /// <param name="encryptionSettings">The encryption settings JSON, or null for the defaults.</param>+ /// <returns>The derived key as 32 bytes.</returns>+ /// <exception cref="InvalidOperationException">Thrown if WASM module is unavailable.</exception>+ public async Task<byte[]> Argon2DeriveKeyAsync(string password, string salt, string? encryptionSettings = null)+ {+ if (!await WaitForAvailabilityAsync())+ {+ throw new InvalidOperationException("Rust WASM module is not available.");+ }++ return await jsRuntime.InvokeAsync<byte[]>("rustCoreArgon2DeriveKey", password, salt, encryptionSettings ?? string.Empty);+ }+/// <summary>/// Generate a random salt for SRP registration./// </summary>diff --git a/apps/server/AliasVault.Client/wwwroot/js/rustCoreInterop.js b/apps/server/AliasVault.Client/wwwroot/js/rustCoreInterop.jsindex cd2b4243f..fb1a95c53 100644--- a/apps/server/AliasVault.Client/wwwroot/js/rustCoreInterop.js+++ b/apps/server/AliasVault.Client/wwwroot/js/rustCoreInterop.js@@ -426,6 +426,33 @@ window.rustCoreGetIdentityAgeRanges = async function() {}};+// ============================================================================+// Argon2id Key Derivation Functions+// ============================================================================++/**+ * Derive a key from a password using Argon2id.+ *+ * The salt is hashed as the characters of the string the server sent, not as the+ * bytes it decodes to, which is what every AliasVault client has always done.+ * @param {string} password - The password, hashed as its UTF-8 bytes.+ * @param {string} salt - The salt, hashed as its UTF-8 bytes.+ * @param {string} encryptionSettings - The EncryptionSettings JSON, or an empty string for the defaults.+ * @returns {Promise<Uint8Array>} The derived key as 32 bytes.+ */+window.rustCoreArgon2DeriveKey = async function(password, salt, encryptionSettings) {+ if (!await initRustCore()) {+ throw new Error('Rust WASM module not available');+ }++ try {+ return wasmModule.argon2DeriveKey(password, salt, encryptionSettings);+ } catch (error) {+ console.error('[RustCore] Argon2 derive key failed:', error);+ throw error;+ }+};+// ============================================================================// SRP (Secure Remote Password) Functions// ============================================================================diff --git a/apps/server/Tests/AliasVault.E2ETests/Tests/Extensions/TestVaultGeneratorTests.cs b/apps/server/Tests/AliasVault.E2ETests/Tests/Extensions/TestVaultGeneratorTests.csindex 1595cfd6d..34e06f737 100644--- a/apps/server/Tests/AliasVault.E2ETests/Tests/Extensions/TestVaultGeneratorTests.cs+++ b/apps/server/Tests/AliasVault.E2ETests/Tests/Extensions/TestVaultGeneratorTests.cs@@ -9,7 +9,6 @@ namespace AliasVault.E2ETests.Tests.Extensions;using System.Diagnostics;using System.Reflection;-using AliasVault.Cryptography.Client;using Microsoft.EntityFrameworkCore;/// <summary>@@ -143,15 +142,17 @@ public class TestVaultGeneratorTests : BrowserExtensionPlaywrightTestvar tempVaultPath = Path.Combine(vaultOutputDir, "test-encrypted-vault.txt");await File.WriteAllTextAsync(tempVaultPath, vault.VaultBlob);- // Generate the decryption key using the same method as the login page- var decryptionKey = await Encryption.DeriveKeyFromPasswordAsync(- TestUserPassword,- vault.Salt,- vault.EncryptionType,- vault.EncryptionSettings);-- // Convert the key to base64 which is how its expected by the other test suites.- var decryptionKeyBase64 = Convert.ToBase64String(decryptionKey);+ /*+ * Derive the decryption key through the client's own Rust WASM binding, the same call the+ * login page makes, so the key printed below cannot drift from what the app derives. The+ * page returns it base64 encoded, which is how the other test suites expect it.+ */+ var decryptionKeyBase64 = await Page.EvaluateAsync<string>(+ @"async ([password, salt, settings]) => {+ const key = await window.rustCoreArgon2DeriveKey(password, salt, settings);+ return btoa(String.fromCharCode(...key));+ }",+ new[] { TestUserPassword, vault.Salt ?? string.Empty, vault.EncryptionSettings ?? string.Empty });Console.WriteLine("\n=== TEST VAULT GENERATION COMPLETE ===");Console.WriteLine("Test vault has been generated with the following details:");diff --git a/apps/server/Tests/AliasVault.UnitTests/Utilities/SrpArgonEncryptionTests.cs b/apps/server/Tests/AliasVault.UnitTests/Utilities/SrpEncryptionTests.cssimilarity index 97%rename from apps/server/Tests/AliasVault.UnitTests/Utilities/SrpArgonEncryptionTests.csrename to apps/server/Tests/AliasVault.UnitTests/Utilities/SrpEncryptionTests.csindex 43cc33b24..25ec6c041 100644--- a/apps/server/Tests/AliasVault.UnitTests/Utilities/SrpArgonEncryptionTests.cs+++ b/apps/server/Tests/AliasVault.UnitTests/Utilities/SrpEncryptionTests.cs@@ -1,5 +1,5 @@//------------------------------------------------------------------------// <copyright file="SrpArgonEncryptionTests.cs" company="aliasvault">+// <copyright file="SrpEncryptionTests.cs" company="aliasvault">// Copyright (c) aliasvault. All rights reserved.// Licensed under the AGPLv3 license. See LICENSE.md file in the project root for full license information.// </copyright>@@ -8,20 +8,20 @@namespace AliasVault.UnitTests.Utilities;using System.Security.Cryptography;+using System.Text;using AliasVault.Cryptography.Client;using SecureRemotePassword;/// <summary>-/// Tests for the SrpArgonEncryption class.+/// Tests for the SRP protocol and the symmetric encryption the server shares with the clients./// </summary>-public class SrpArgonEncryptionTests+public class SrpEncryptionTests{/// <summary>- /// Test basic encryption and decryption using default encryption logic (Argon2id and AES-256).+ /// Test basic encryption and decryption using default encryption logic (AES-256)./// </summary>- /// <returns>Task.</returns>[Test]- public async Task TestBasicEncrypt()+ public void TestBasicEncrypt(){var stopwatch = System.Diagnostics.Stopwatch.StartNew();string password = "your-password";@@ -29,8 +29,7 @@ public class SrpArgonEncryptionTestsstring plaintext = "Hello, World!";- // Derive a key from the password using Argon2id- byte[] key = await Encryption.DeriveKeyFromPasswordAsync(password, salt);+ byte[] key = DeriveTestKey(password, salt);Console.WriteLine($"Derived key: {key.Length} bytes (hex: {Convert.ToHexString(key).Replace("-", string.Empty)})");// SymmetricEncrypt the plaintext@@ -70,25 +69,23 @@ public class SrpArgonEncryptionTests}/// <summary>- /// Test basic encryption and decryption using default encryption logic (Argon2id and AES-256).+ /// Test that a key derived from a different password cannot decrypt the ciphertext./// </summary>- /// <returns>Task.</returns>[Test]- public async Task TestNotEqualsPassword()+ public void TestNotEqualsPassword(){string password = "your-password";string salt = "your-salt"; // Use a secure random salt in productionstring plaintext = "Hello, World!";- // Derive a key from the password using Argon2id- byte[] key = await Cryptography.Client.Encryption.DeriveKeyFromPasswordAsync(password, salt);+ byte[] key = DeriveTestKey(password, salt);// SymmetricEncrypt the plaintextstring encrypted = Cryptography.Server.Encryption.SymmetricEncrypt(plaintext, key);// SymmetricDecrypt the ciphertext using a different key- byte[] key2 = await Cryptography.Client.Encryption.DeriveKeyFromPasswordAsync("your-password2", salt);+ byte[] key2 = DeriveTestKey("your-password2", salt);Assert.Throws<AuthenticationTagMismatchException>(() => Cryptography.Server.Encryption.SymmetricDecrypt(encrypted, key2));}@@ -96,9 +93,8 @@ public class SrpArgonEncryptionTests/// <summary>/// Test the SRP authentication flow to ensure it works correctly./// </summary>- /// <returns>Async task.</returns>[Test]- public async Task TestSrpAuthentication()+ public void TestSrpAuthentication(){var email = "[email protected]";var password = "myPassword";@@ -108,7 +104,7 @@ public class SrpArgonEncryptionTestsvar client = new SrpClient();var salt = client.GenerateSalt();- byte[] passwordHash = await Cryptography.Client.Encryption.DeriveKeyFromPasswordAsync(password, salt);+ byte[] passwordHash = DeriveTestKey(password, salt);var passwordHashString = Convert.ToHexString(passwordHash).Replace("-", string.Empty);var srpSignup = Srp.PasswordChangeAsync(client, salt, email, passwordHashString);@@ -148,15 +144,13 @@ public class SrpArgonEncryptionTests/// <summary>/// Test byte array encryption and decryption overload methods./// </summary>- /// <returns>Task.</returns>[Test]- public async Task TestByteArrayEncryption()+ public void TestByteArrayEncryption(){string password = "your-password";string salt = "your-salt";- // Derive a key from the password using Argon2id- byte[] key = await Cryptography.Client.Encryption.DeriveKeyFromPasswordAsync(password, salt);+ byte[] key = DeriveTestKey(password, salt);// Generate random byte array of 1000 bytesbyte[] plainBytes = new byte[1000];@@ -173,4 +167,14 @@ public class SrpArgonEncryptionTestsvar decrypted = Cryptography.Server.Encryption.SymmetricDecrypt(cipherBytes, key);Assert.That(decrypted, Is.EqualTo(plainBytes));}++ /// <summary>+ /// Derives a deterministic 32-byte key from a password and salt. The key derivation the+ /// clients ship lives in the Rust core; these tests only need a key to encrypt with, so they+ /// do not pull in a second Argon2 implementation to get one.+ /// </summary>+ /// <param name="password">Password.</param>+ /// <param name="salt">Salt.</param>+ /// <returns>The derived key as 32 bytes.</returns>+ private static byte[] DeriveTestKey(string password, string salt) => SHA256.HashData(Encoding.UTF8.GetBytes(password + salt));}diff --git a/apps/server/Utilities/Cryptography/AliasVault.Cryptography.Client/AliasVault.Cryptography.Client.csproj b/apps/server/Utilities/Cryptography/AliasVault.Cryptography.Client/AliasVault.Cryptography.Client.csprojindex 56c1a10eb..aa6d292e4 100644--- a/apps/server/Utilities/Cryptography/AliasVault.Cryptography.Client/AliasVault.Cryptography.Client.csproj+++ b/apps/server/Utilities/Cryptography/AliasVault.Cryptography.Client/AliasVault.Cryptography.Client.csproj@@ -24,7 +24,6 @@</ItemGroup><ItemGroup>- <PackageReference Include="Konscious.Security.Cryptography.Argon2" Version="1.3.1" /><PackageReference Include="srp" Version="1.0.7" /><PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.556"><PrivateAssets>all</PrivateAssets>diff --git a/apps/server/Utilities/Cryptography/AliasVault.Cryptography.Client/Encryption.cs b/apps/server/Utilities/Cryptography/AliasVault.Cryptography.Client/Encryption.csdeleted file mode 100644index 26f581750..000000000--- a/apps/server/Utilities/Cryptography/AliasVault.Cryptography.Client/Encryption.cs+++ /dev/null@@ -1,92 +0,0 @@-//------------------------------------------------------------------------// <copyright file="Encryption.cs" company="aliasvault">-// Copyright (c) aliasvault. All rights reserved.-// Licensed under the AGPLv3 license. See LICENSE.md file in the project root for full license information.-// </copyright>-//-------------------------------------------------------------------------namespace AliasVault.Cryptography.Client;--using System.Text;-using System.Text.Json;-using Konscious.Security.Cryptography;--/// <summary>-/// Key derivation algorithms used for encryption/decryption.-/// </summary>-public static class Encryption-{- /// <summary>- /// Derive a key used for encryption/decryption based on a user password and system salt.- /// </summary>- /// <param name="password">User password.</param>- /// <param name="salt">The salt to use for the Argon2id hash.</param>- /// <param name="encryptionType">The encryption type to use. Defaults to <see cref="Defaults.EncryptionType"/>.</param>- /// <param name="encryptionSettings">The encryption settings to use. Defaults to settings as defined in <see cref="Defaults"/>.</param>- /// <returns>Key derived from plain-text password as byte array.</returns>- public static async Task<byte[]> DeriveKeyFromPasswordAsync(string password, string salt, string? encryptionType = null, string? encryptionSettings = null)- {- if (encryptionType is null)- {- encryptionType = Defaults.EncryptionType;- }-- byte[] passwordBytes = Encoding.UTF8.GetBytes(password);- byte[] saltBytes = Encoding.UTF8.GetBytes(salt);-- switch (encryptionType)- {- case "Argon2Id":- return await Argon2Id(passwordBytes, saltBytes, encryptionSettings);- default:- throw new NotSupportedException($"Encryption type {encryptionType} is not supported.");- }- }-- /// <summary>- /// Derive a key using Argon2id algorithm.- /// </summary>- /// <param name="passwordBytes">Password bytes.</param>- /// <param name="saltBytes">Salt bytes.</param>- /// <param name="encryptionSettings">Encryption settings JSON string.</param>- /// <returns>Key derived from plain-text password as byte array.</returns>- private static async Task<byte[]> Argon2Id(byte[] passwordBytes, byte[] saltBytes, string? encryptionSettings = null)- {- var degreeOfParallelism = Defaults.Argon2IdDegreeOfParallelism;- var memorySize = Defaults.Argon2IdMemorySize;- var iterations = Defaults.Argon2IdIterations;-- if (encryptionSettings is not null)- {- // Parse the encryption properties json string.- var properties = JsonSerializer.Deserialize<Dictionary<string, int>>(encryptionSettings);- if (properties is not null)- {- if (properties.TryGetValue("DegreeOfParallelism", out int doP))- {- degreeOfParallelism = doP;- }-- if (properties.TryGetValue("MemorySize", out int memSize))- {- memorySize = memSize;- }-- if (properties.TryGetValue("Iterations", out int iter))- {- iterations = iter;- }- }- }-- var argon2 = new Argon2id(passwordBytes)- {- Salt = saltBytes,- DegreeOfParallelism = degreeOfParallelism,- MemorySize = memorySize,- Iterations = iterations,- };-- return await argon2.GetBytesAsync(32); // Generate a 256-bit key- }-}