Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Code style refactor (#117)
Leendert de Borst31429fb5f5fe
diff --git a/src/AliasVault.Api/Controllers/EmailBoxController.cs b/src/AliasVault.Api/Controllers/EmailBoxController.csindex 8e6a1971a..d44c1dd6a 100644--- a/src/AliasVault.Api/Controllers/EmailBoxController.cs+++ b/src/AliasVault.Api/Controllers/EmailBoxController.cs@@ -49,7 +49,7 @@ public class EmailBoxController(IDbContextFactory<AliasServerDbContext> dbContex}// Retrieve emails from database.- List<MailboxEmailApiModel> emails = context.Emails.AsNoTracking().Select(x => new MailboxEmailApiModel()+ List<MailboxEmailApiModel> emails = await context.Emails.AsNoTracking().Select(x => new MailboxEmailApiModel(){Id = x.Id,Subject = x.Subject,@@ -64,7 +64,7 @@ public class EmailBoxController(IDbContextFactory<AliasServerDbContext> dbContexMessagePreview = x.MessagePreview ?? string.Empty,EncryptedSymmetricKey = x.EncryptedSymmetricKey,EncryptionKey = x.EncryptionKey.PublicKey,- }).OrderByDescending(x => x.DateSystem).Take(75).ToList();+ }).OrderByDescending(x => x.DateSystem).Take(75).ToListAsync();MailboxApiModel returnValue = new MailboxApiModel();returnValue.Address = to;diff --git a/src/AliasVault.Api/Controllers/EmailController.cs b/src/AliasVault.Api/Controllers/EmailController.csindex fdbe77a6e..8d2c79b7f 100644--- a/src/AliasVault.Api/Controllers/EmailController.cs+++ b/src/AliasVault.Api/Controllers/EmailController.cs@@ -74,14 +74,14 @@ public class EmailController(IDbContextFactory<AliasServerDbContext> dbContextFa};// Add attachment metadata (without the filebytes)- var attachments = context.EmailAttachments.Where(x => x.EmailId == email.Id).Select(x => new AttachmentApiModel()+ var attachments = await context.EmailAttachments.Where(x => x.EmailId == email.Id).Select(x => new AttachmentApiModel(){Id = x.Id,Email_Id = x.EmailId,Filename = x.Filename,MimeType = x.MimeType,Filesize = x.Filesize,- }).ToList();+ }).ToListAsync();returnEmail.Attachments = attachments;diff --git a/src/AliasVault.Api/Helpers/ConversionHelper.cs b/src/AliasVault.Api/Helpers/ConversionHelper.csindex d8df8357d..2186521b7 100644--- a/src/AliasVault.Api/Helpers/ConversionHelper.cs+++ b/src/AliasVault.Api/Helpers/ConversionHelper.cs@@ -8,12 +8,11 @@namespace AliasVault.Api.Helpers;using System.Text.RegularExpressions;-using AliasServerDb;/// <summary>/// Class which contains various helper methods for data conversion./// </summary>-public class ConversionHelper+public static class ConversionHelper{/// <summary>/// Extract only displayname from full "From" string. E.g. "John Doe" [[email protected]] becomes "John Doe".@@ -24,17 +23,19 @@ public class ConversionHelper{// Get the display name from the From field, which is everything before the first < and after the first >string fromDisplay = from;- if (from.Contains("<"))+ if (!from.Contains('<')){- // Remove everything after the last < until the last >- fromDisplay = from.Substring(0, from.LastIndexOf("<", StringComparison.Ordinal));+ return fromDisplay;+ }- // Remove any double quotes- fromDisplay = fromDisplay.Replace("\"", string.Empty);+ // Remove everything after the last < until the last >+ fromDisplay = from.Substring(0, from.LastIndexOf('<'));- // Trim any whitespace- fromDisplay = fromDisplay.Trim();- }+ // Remove any double quotes+ fromDisplay = fromDisplay.Replace("\"", string.Empty);++ // Trim any whitespace+ fromDisplay = fromDisplay.Trim();return fromDisplay;}@@ -51,7 +52,8 @@ public class ConversionHelperhtml,@"<a\s+(.*?)href=([""'])(.*?)\2(.*?)>",m => $"<a {m.Groups[1].Value}href={m.Groups[2].Value}{m.Groups[3].Value}{m.Groups[2].Value} {m.Groups[4].Value} target=\"_blank\">",- RegexOptions.IgnoreCase | RegexOptions.Singleline);+ RegexOptions.IgnoreCase | RegexOptions.Singleline,+ TimeSpan.FromSeconds(1));return html;}diff --git a/src/AliasVault.Client/Main/Components/Email/EmailModal.razor b/src/AliasVault.Client/Main/Components/Email/EmailModal.razorindex 3e9697ea5..22e20c17a 100644--- a/src/AliasVault.Client/Main/Components/Email/EmailModal.razor+++ b/src/AliasVault.Client/Main/Components/Email/EmailModal.razor@@ -3,7 +3,7 @@<div class="fixed inset-0 z-50 overflow-auto bg-gray-500 bg-opacity-75 flex items-center justify-center"><div class="relative p-8 bg-white w-full max-w-md flex-col flex rounded-lg shadow-xl"><div class="flex items-center justify-between">- <h2 class="text-2xl font-bold text-gray-900 dark:text-white"><a target="_blank" href="https://spamok.com/@(Email!.ToLocal)/@(Email!.Id)">@Email?.Subject</a></h2>+ <h2 class="text-2xl font-bold text-gray-900 dark:text-white"><a target="_blank" href="https://spamok.com/@(Email!.ToLocal)/@(Email!.Id)">@Email.Subject</a></h2><button @onclick="Close" class="text-gray-400 hover:text-gray-500"><svg class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>@@ -11,8 +11,8 @@</button></div><div class="mt-4">- <p class="text-sm text-gray-500 dark:text-gray-400">From: @Email?.FromDisplay</p>- <p class="text-sm text-gray-500 dark:text-gray-400">Date: @Email?.DateSystem</p>+ <p class="text-sm text-gray-500 dark:text-gray-400">From: @Email.FromDisplay</p>+ <p class="text-sm text-gray-500 dark:text-gray-400">Date: @Email.DateSystem</p></div><div class="mt-4 text-gray-700 dark:text-gray-300"><div>diff --git a/src/AliasVault.Client/Main/Components/Email/RecentEmails.razor b/src/AliasVault.Client/Main/Components/Email/RecentEmails.razorindex f55bc74e5..6e71f6c29 100644--- a/src/AliasVault.Client/Main/Components/Email/RecentEmails.razor+++ b/src/AliasVault.Client/Main/Components/Email/RecentEmails.razor@@ -98,10 +98,26 @@}}+ /// <inheritdoc />+ protected override async Task OnAfterRenderAsync(bool firstRender)+ {+ await base.OnAfterRenderAsync(firstRender);++ if (!ShowComponent)+ {+ return;+ }++ if (firstRender)+ {+ await LoadRecentEmailsAsync();+ }+ }+/// <summary>/// Returns true if the email address is from a known SpamOK domain./// </summary>- protected bool IsSpamOkDomain(string email)+ private bool IsSpamOkDomain(string email){return email.EndsWith("@spamok.nl") ||email.EndsWith("@spamok.de") ||@@ -119,33 +135,9 @@/// <summary>/// Returns true if the email address is from a known AliasVault domain./// </summary>- protected bool IsAliasVaultDomain(string email)+ private bool IsAliasVaultDomain(string email){- foreach (var domain in Config.SmtpAllowedDomains)- {- if (email.EndsWith(domain))- {- return true;- }- }-- return false;- }-- /// <inheritdoc />- protected override async Task OnAfterRenderAsync(bool firstRender)- {- await base.OnAfterRenderAsync(firstRender);-- if (!ShowComponent)- {- return;- }-- if (firstRender)- {- await LoadRecentEmailsAsync();- }+ return Config.SmtpAllowedDomains.Any(x => email.EndsWith(x));}private async Task LoadRecentEmailsAsync()@@ -156,65 +148,19 @@}Error = string.Empty;-IsLoading = true;StateHasChanged();// Get email prefix, which is the part before the @ symbol.string emailPrefix = EmailAddress.Split('@')[0];- MailboxApiModel? mailbox = new();-if (IsSpamOkDomain(EmailAddress)){- // We construct a new HttpClient to avoid using the default one, which is used for the API and sends- // the Authorization header. We don't want to send the Authorization header to the external email API.- var client = HttpClientFactory.CreateClient("EmailClient");- mailbox = await client.GetFromJsonAsync<MailboxApiModel>($"https://api.spamok.com/v2/EmailBox/{emailPrefix}");-- if (mailbox?.Mails != null)- {- // Show maximum of 10 recent emails.- MailboxEmails = mailbox.Mails.Take(10).ToList();- }+ await LoadSpamOkEmails(emailPrefix);}else if (IsAliasVaultDomain(EmailAddress)){- try- {- mailbox = await HttpClient.GetFromJsonAsync<MailboxApiModel>($"api/v1/EmailBox/{EmailAddress}");- if (mailbox?.Mails != null)- {- // Show maximum of 10 recent emails.- MailboxEmails = mailbox.Mails.Take(10).ToList();- }-- // Loop through emails and decrypt the subject locally.- var context = await DbService.GetDbContextAsync();- var privateKeys = await context.EncryptionKeys.ToListAsync();- foreach (var mail in MailboxEmails)- {- var privateKey = privateKeys.FirstOrDefault(x => x.PublicKey == mail.EncryptionKey);- if (privateKey is not null)- {- try- {- var decryptedSymmetricKey = await JsInteropService.DecryptWithPrivateKey(mail.EncryptedSymmetricKey, privateKey.PrivateKey);- mail.Subject = await JsInteropService.SymmetricDecrypt(mail.Subject, Convert.ToBase64String(decryptedSymmetricKey));- }- catch (Exception ex)- {- Error = ex.Message;- Console.WriteLine(ex);- }- }- }- }- catch (Exception ex)- {- Error = ex.Message;- Console.WriteLine(ex);- }+ await LoadAliasVaultEmails();}IsLoading = false;@@ -232,56 +178,127 @@if (IsSpamOkDomain(EmailAddress)){- var client = HttpClientFactory.CreateClient("EmailClient");- EmailApiModel? mail = await client.GetFromJsonAsync<EmailApiModel>($"https://api.spamok.com/v2/Email/{emailPrefix}/{emailId}");- if (mail != null)+ await ShowSpamOkEmailInModal(emailPrefix, emailId);+ }+ else if (IsAliasVaultDomain(EmailAddress))+ {+ await ShowAliasVaultEmailInModal(emailId);+ }+ }++ /// <summary>+ /// Load recent emails from SpamOK.+ /// </summary>+ private async Task LoadSpamOkEmails(string emailPrefix)+ {+ // We construct a new HttpClient to avoid using the default one, which is used for the API and sends+ // the Authorization header. We don't want to send the Authorization header to the external email API.+ var client = HttpClientFactory.CreateClient("EmailClient");+ var mailbox = await client.GetFromJsonAsync<MailboxApiModel>($"https://api.spamok.com/v2/EmailBox/{emailPrefix}");++ if (mailbox?.Mails != null)+ {+ // Show maximum of 10 recent emails.+ MailboxEmails = mailbox.Mails.Take(10).ToList();+ }+ }++ /// <summary>+ /// Load recent emails from SpamOK.+ /// </summary>+ private async Task ShowSpamOkEmailInModal(string emailPrefix, int emailId)+ {+ var client = HttpClientFactory.CreateClient("EmailClient");+ EmailApiModel? mail = await client.GetFromJsonAsync<EmailApiModel>($"https://api.spamok.com/v2/Email/{emailPrefix}/{emailId}");+ if (mail != null)+ {+ Email = mail;+ EmailModalVisible = true;+ StateHasChanged();+ }+ }++ /// <summary>+ /// Load recent emails from AliasVault.+ /// </summary>+ private async Task LoadAliasVaultEmails()+ {+ try+ {+ var mailbox = await HttpClient.GetFromJsonAsync<MailboxApiModel>($"api/v1/EmailBox/{EmailAddress}");+ if (mailbox?.Mails != null){- Email = mail;- EmailModalVisible = true;- StateHasChanged();+ // Show maximum of 10 recent emails.+ MailboxEmails = mailbox.Mails.Take(10).ToList();+ }++ // Loop through emails and decrypt the subject locally.+ var context = await DbService.GetDbContextAsync();+ var privateKeys = await context.EncryptionKeys.ToListAsync();+ foreach (var mail in MailboxEmails)+ {+ var privateKey = privateKeys.First(x => x.PublicKey == mail.EncryptionKey);++ try+ {+ var decryptedSymmetricKey = await JsInteropService.DecryptWithPrivateKey(mail.EncryptedSymmetricKey, privateKey.PrivateKey);+ mail.Subject = await JsInteropService.SymmetricDecrypt(mail.Subject, Convert.ToBase64String(decryptedSymmetricKey));+ }+ catch (Exception ex)+ {+ Error = ex.Message;+ Console.WriteLine(ex);+ }}}- else if (IsAliasVaultDomain(EmailAddress))+ catch (Exception ex){- EmailApiModel? mail = await HttpClient.GetFromJsonAsync<EmailApiModel>($"api/v1/Email/{emailId}");- if (mail != null)+ Error = ex.Message;+ Console.WriteLine(ex);+ }+ }++ /// <summary>+ /// Load recent emails from AliasVault.+ /// </summary>+ private async Task ShowAliasVaultEmailInModal(int emailId)+ {+ EmailApiModel? mail = await HttpClient.GetFromJsonAsync<EmailApiModel>($"api/v1/Email/{emailId}");+ if (mail != null)+ {+ // Decrypt the email content locally.+ var context = await DbService.GetDbContextAsync();+ var privateKey = await context.EncryptionKeys.FirstOrDefaultAsync(x => x.PublicKey == mail.EncryptionKey);+ if (privateKey is not null){- // Decrypt the email content locally.- var context = await DbService.GetDbContextAsync();- var privateKey = await context.EncryptionKeys.FirstOrDefaultAsync(x => x.PublicKey == mail.EncryptionKey);- if (privateKey is not null)+ try{- try+ var decryptedSymmetricKey = await JsInteropService.DecryptWithPrivateKey(mail.EncryptedSymmetricKey, privateKey.PrivateKey);+ mail.Subject = await JsInteropService.SymmetricDecrypt(mail.Subject, Convert.ToBase64String(decryptedSymmetricKey));+ if (mail.MessageHtml is not null){- var decryptedSymmetricKey = await JsInteropService.DecryptWithPrivateKey(mail.EncryptedSymmetricKey, privateKey.PrivateKey);- mail.Subject = await JsInteropService.SymmetricDecrypt(mail.Subject, Convert.ToBase64String(decryptedSymmetricKey));- if (mail.MessageHtml is not null)- {- mail.MessageHtml = await JsInteropService.SymmetricDecrypt(mail.MessageHtml, Convert.ToBase64String(decryptedSymmetricKey));- }-- if (mail.MessagePlain is not null)- {- mail.MessagePlain = await JsInteropService.SymmetricDecrypt(mail.MessagePlain, Convert.ToBase64String(decryptedSymmetricKey));- }-- mail.FromDisplay = await JsInteropService.SymmetricDecrypt(mail.FromDisplay, Convert.ToBase64String(decryptedSymmetricKey));- mail.FromLocal = await JsInteropService.SymmetricDecrypt(mail.FromLocal, Convert.ToBase64String(decryptedSymmetricKey));- mail.FromDomain = await JsInteropService.SymmetricDecrypt(mail.FromDomain, Convert.ToBase64String(decryptedSymmetricKey));+ mail.MessageHtml = await JsInteropService.SymmetricDecrypt(mail.MessageHtml, Convert.ToBase64String(decryptedSymmetricKey));}- catch (Exception ex)++ if (mail.MessagePlain is not null){- Error = ex.Message;+ mail.MessagePlain = await JsInteropService.SymmetricDecrypt(mail.MessagePlain, Convert.ToBase64String(decryptedSymmetricKey));}- }- Email = mail;- EmailModalVisible = true;- StateHasChanged();+ mail.FromDisplay = await JsInteropService.SymmetricDecrypt(mail.FromDisplay, Convert.ToBase64String(decryptedSymmetricKey));+ mail.FromLocal = await JsInteropService.SymmetricDecrypt(mail.FromLocal, Convert.ToBase64String(decryptedSymmetricKey));+ mail.FromDomain = await JsInteropService.SymmetricDecrypt(mail.FromDomain, Convert.ToBase64String(decryptedSymmetricKey));+ }+ catch (Exception ex)+ {+ Error = ex.Message;+ }}+ Email = mail;+ EmailModalVisible = true;+ StateHasChanged();}-}/// <summary>diff --git a/src/AliasVault.Client/Services/Database/DbService.cs b/src/AliasVault.Client/Services/Database/DbService.csindex 30e332e84..b73447e91 100644--- a/src/AliasVault.Client/Services/Database/DbService.cs+++ b/src/AliasVault.Client/Services/Database/DbService.cs@@ -460,7 +460,7 @@ public class DbService : IDisposable// Filter the list of email addresses to only include those that are in the allowed domains.emailAddresses = emailAddresses- .Where(email => _config.SmtpAllowedDomains.Any(domain => email.EndsWith(domain)))+ .Where(email => _config.SmtpAllowedDomains.Exists(domain => email.EndsWith(domain))).ToList();var databaseVersion = await GetCurrentDatabaseVersionAsync();diff --git a/src/AliasVault.Client/Services/JsInteropService.cs b/src/AliasVault.Client/Services/JsInteropService.csindex 677c077cf..a27dfbb14 100644--- a/src/AliasVault.Client/Services/JsInteropService.cs+++ b/src/AliasVault.Client/Services/JsInteropService.cs@@ -106,7 +106,7 @@ public class JsInteropService(IJSRuntime jsRuntime)}catch (JSException ex){- Console.Error.WriteLine($"JavaScript decryption error: {ex.Message}");+ await Console.Error.WriteLineAsync($"JavaScript decryption error: {ex.Message}");throw new CryptographicException("Decryption failed", ex);}}diff --git a/src/Services/AliasVault.SmtpService/Handlers/DatabaseMessageStore.cs b/src/Services/AliasVault.SmtpService/Handlers/DatabaseMessageStore.csindex e0807742e..008b47ae1 100644--- a/src/Services/AliasVault.SmtpService/Handlers/DatabaseMessageStore.cs+++ b/src/Services/AliasVault.SmtpService/Handlers/DatabaseMessageStore.cs@@ -93,7 +93,7 @@ public class DatabaseMessageStore(ILogger<DatabaseMessageStore> logger, Config c}// Check if the local part of the toAddress is a known alias (claimed by a user)- var dbContext = await dbContextFactory.CreateDbContextAsync();+ var dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);var userEmailClaim = await dbContext.UserEmailClaims.FirstOrDefaultAsync(x =>x.AddressLocal == toAddress.User.ToLowerInvariant() &&x.AddressDomain == toAddress.Host.ToLowerInvariant());@@ -115,7 +115,7 @@ public class DatabaseMessageStore(ILogger<DatabaseMessageStore> logger, Config c}// Retrieve user public encryption key from database- var userPublicKey = dbContext.UserEncryptionKeys.FirstOrDefault(x =>+ var userPublicKey = await dbContext.UserEncryptionKeys.FirstOrDefaultAsync(x =>x.UserId == userEmailClaim.UserId && x.IsPrimary);if (userPublicKey is null)diff --git a/src/Tests/AliasVault.E2ETests/Common/ClientPlaywrightTest.cs b/src/Tests/AliasVault.E2ETests/Common/ClientPlaywrightTest.csindex 1277705b4..214017721 100644--- a/src/Tests/AliasVault.E2ETests/Common/ClientPlaywrightTest.cs+++ b/src/Tests/AliasVault.E2ETests/Common/ClientPlaywrightTest.cs@@ -89,6 +89,8 @@ public class ClientPlaywrightTest : PlaywrightTestawait SetupPlaywrightBrowserAndContext();// Intercept Blazor WASM app requests to override appsettings.json+ string[] smtpAllowedDomains = ["example.tld"];+await Context.RouteAsync("**/appsettings.json",async route =>@@ -96,7 +98,7 @@ public class ClientPlaywrightTest : PlaywrightTestvar response = new{ApiUrl = ApiBaseUrl.TrimEnd('/'),- SmtpAllowedDomains = new string[] { "example.tld" },+ SmtpAllowedDomains = smtpAllowedDomains,};await route.FulfillAsync(new RouteFulfillOptions@@ -112,7 +114,7 @@ public class ClientPlaywrightTest : PlaywrightTestvar response = new{ApiUrl = ApiBaseUrl.TrimEnd('/'),- SmtpAllowedDomains = new string[] { "example.tld" },+ SmtpAllowedDomains = smtpAllowedDomains,};await route.FulfillAsync(new RouteFulfillOptionsdiff --git a/src/Tests/AliasVault.UnitTests/Utilities/RsaEncryptionTests.cs b/src/Tests/AliasVault.UnitTests/Utilities/RsaEncryptionTests.csindex e52e7c1c6..30b2f3add 100644--- a/src/Tests/AliasVault.UnitTests/Utilities/RsaEncryptionTests.cs+++ b/src/Tests/AliasVault.UnitTests/Utilities/RsaEncryptionTests.cs@@ -7,7 +7,6 @@namespace AliasVault.Tests.Utilities;-using System.Security.Cryptography;using System.Text.Json;using Cryptography;@@ -72,116 +71,6 @@ public class RsaEncryptionTestsAssert.That(() => JsonSerializer.Deserialize<Dictionary<string, object>>(PrivateKey), Throws.Nothing);}- /// <summary>- /// Tests that encryption with public key followed by decryption with private key returns the original plaintext.- /// </summary>- [Test]- public void EncryptWithPublicKey_DecryptWithPrivateKey_ShouldReturnOriginalPlaintext()- {- // Example public and private keys as generated by the JSInterop on the client.- string originalPlaintext = "Hello, RSA encryption!";-- string ciphertext = Encryption.EncryptWithPublicKey(originalPlaintext, PublicKey);- string decryptedText = Encryption.DecryptWithPrivateKey(ciphertext, PrivateKey);-- Assert.That(decryptedText, Is.EqualTo(originalPlaintext));- }-- /// <summary>- /// Tests that encrypting the same plaintext twice produces different ciphertexts.- /// </summary>- [Test]- public void EncryptWithPublicKey_ShouldProduceDifferentCiphertextForSamePlaintext()- {- string plaintext = "Same plaintext";-- string ciphertext1 = Encryption.EncryptWithPublicKey(plaintext, PublicKey);- string ciphertext2 = Encryption.EncryptWithPublicKey(plaintext, PublicKey);-- Assert.That(ciphertext2, Is.Not.EqualTo(ciphertext1));- }-- /// <summary>- /// Tests that decrypting an invalid ciphertext throws an exception.- /// </summary>- [Test]- public void DecryptWithPrivateKey_ShouldThrowExceptionForInvalidCiphertext()- {- string invalidCiphertext = "ThisIsNotValidCiphertext";-- Assert.That(- () => Encryption.DecryptWithPrivateKey(invalidCiphertext, PrivateKey),- Throws.TypeOf<CryptographicException>());- }-- /// <summary>- /// Tests encryption and decryption with a long plaintext string.- /// </summary>- [Test]- public void EncryptDecrypt_ShouldWorkWithLongPlaintext()- {- string longPlaintext = new string('A', 192); // 192 character string-- string ciphertext = Encryption.EncryptWithPublicKey(longPlaintext, PublicKey);- string decryptedText = Encryption.DecryptWithPrivateKey(ciphertext, PrivateKey);-- Assert.That(decryptedText, Is.EqualTo(longPlaintext));- }-- /// <summary>- /// Tests encryption and decryption with special characters.- /// </summary>- [Test]- public void EncryptDecrypt_ShouldWorkWithSpecialCharacters()- {- string specialChars = "!@#$%^&*()_+{}[]|\\:;\"'<>,.?/~`";-- string ciphertext = Encryption.EncryptWithPublicKey(specialChars, PublicKey);- string decryptedText = Encryption.DecryptWithPrivateKey(ciphertext, PrivateKey);-- Assert.That(decryptedText, Is.EqualTo(specialChars));- }-- /// <summary>- /// Tests encryption and decryption with Unicode characters from different languages.- /// </summary>- [Test]- public void EncryptDecrypt_ShouldWorkWithUnicodeCharacters()- {- string unicodeText = "こんにちは世界! - Здравствуй, мир! - مرحبا بالعالم! - 你好,世界!";-- string ciphertext = Encryption.EncryptWithPublicKey(unicodeText, PublicKey);- string decryptedText = Encryption.DecryptWithPrivateKey(ciphertext, PrivateKey);-- Assert.That(decryptedText, Is.EqualTo(unicodeText));- }-- /// <summary>- /// Tests that encrypting with an invalid public key throws an exception.- /// </summary>- [Test]- public void EncryptWithPublicKey_ShouldThrowExceptionForInvalidPublicKey()- {- string invalidPublicKey = "ThisIsNotAValidPublicKey";- string plaintext = "Test plaintext";-- Assert.Throws<JsonException>(() => Encryption.EncryptWithPublicKey(plaintext, invalidPublicKey));- }-- /// <summary>- /// Tests that decrypting with an invalid private key throws an exception.- /// </summary>- [Test]- public void DecryptWithPrivateKey_ShouldThrowExceptionForInvalidPrivateKey()- {- string invalidPrivateKey = "ThisIsNotAValidPrivateKey";- string plaintext = "Test plaintext";-- string ciphertext = Encryption.EncryptWithPublicKey(plaintext, PublicKey);-- Assert.Throws<JsonException>(() => Encryption.DecryptWithPrivateKey(ciphertext, invalidPrivateKey));- }-/// <summary>/// Tests if GenerateRandomSymmetricKey method returns a key of correct length./// </summary>diff --git a/src/Utilities/Cryptography/EmailEncryption.cs b/src/Utilities/Cryptography/EmailEncryption.csindex ce796b582..89b622748 100644--- a/src/Utilities/Cryptography/EmailEncryption.cs+++ b/src/Utilities/Cryptography/EmailEncryption.cs@@ -12,7 +12,7 @@ using AliasServerDb;/// <summary>/// Helper class for encrypting and decrypting email contents./// </summary>-public class EmailEncryption+public static class EmailEncryption{/// <summary>/// Encrypt the email contents with the user's public key.diff --git a/src/Utilities/Cryptography/Encryption.cs b/src/Utilities/Cryptography/Encryption.csindex 5dec4775d..5b06c6fe3 100644--- a/src/Utilities/Cryptography/Encryption.cs+++ b/src/Utilities/Cryptography/Encryption.cs@@ -145,40 +145,6 @@ public static class Encryptionreturn Encoding.UTF8.GetString(plaintextBytes).TrimEnd('\0');}- /// <summary>- /// Encrypts a plaintext string using an RSA public key.- /// </summary>- /// <param name="plaintext">The plaintext to encrypt.</param>- /// <param name="publicKey">The public key in XML format.</param>- /// <returns>The encrypted data as a base64-encoded string.</returns>- public static string EncryptWithPublicKey(string plaintext, string publicKey)- {- using (var rsa = new RSACryptoServiceProvider())- {- ImportPublicKey(rsa, publicKey);- byte[] plaintextBytes = Encoding.UTF8.GetBytes(plaintext);- byte[] cipherBytes = rsa.Encrypt(plaintextBytes, true);- return Convert.ToBase64String(cipherBytes);- }- }-- /// <summary>- /// Decrypts a ciphertext string using an RSA private key.- /// </summary>- /// <param name="ciphertext">The base64-encoded ciphertext to decrypt.</param>- /// <param name="privateKey">The private key in XML format.</param>- /// <returns>The decrypted plaintext.</returns>- public static string DecryptWithPrivateKey(string ciphertext, string privateKey)- {- using (var rsa = new RSACryptoServiceProvider())- {- ImportPrivateKey(rsa, privateKey);- byte[] cipherBytes = Convert.FromBase64String(ciphertext);- byte[] plaintextBytes = rsa.Decrypt(cipherBytes, true);- return Encoding.UTF8.GetString(plaintextBytes);- }- }-/// <summary>/// Imports a public key from JWK format into an RSA provider./// </summary>