Skip to content

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

Cleanup AliasVault.Cryptography (#2468)

Leendert de Borsta85d9cbad211
diff --git a/apps/server/Utilities/AliasVault.Cryptography/EmailEncryption.cs b/apps/server/Utilities/AliasVault.Cryptography/EmailEncryption.cs
index a0629e632..b6768f2e8 100644
--- a/apps/server/Utilities/AliasVault.Cryptography/EmailEncryption.cs
+++ b/apps/server/Utilities/AliasVault.Cryptography/EmailEncryption.cs
@@ -11,7 +11,7 @@ using AliasServerDb;
using AliasVault.Shared.Models.Enums;
/// <summary>
-/// Helper class for encrypting and decrypting email contents.
+/// Encrypts incoming email contents for the delivery keys of the recipient manifests.
/// </summary>
public static class EmailEncryption
{
@@ -82,74 +82,4 @@ public static class EmailEncryption
return email;
}
-
- /// <summary>
- /// Decrypt the email contents with the user's private key.
- /// </summary>
- /// <param name="email">The plain text email object to decrypt.</param>
- /// <param name="userPrivateKey">The user private encryption key to use for the decryption.</param>
- /// <returns>Email object with all sensitive fields decrypted.</returns>
- public static Email DecryptEmail(Email email, string userPrivateKey)
- {
- // Decrypt the symmetric key belonging to this private key; with multiple decryption keys the
- // matching one is found by simply trying each.
- byte[]? symmetricKey = null;
- foreach (var decryptionKey in email.DecryptionKeys)
- {
- try
- {
- symmetricKey = Encryption.DecryptSymmetricKeyWithRsa(decryptionKey.EncryptedSymmetricKey, userPrivateKey);
- break;
- }
- catch (System.Security.Cryptography.CryptographicException)
- {
- // The key belongs to another manifest; try the next one.
- }
- }
-
- if (symmetricKey is null)
- {
- throw new InvalidOperationException("The email carries no decryption key that the provided private key can open.");
- }
-
- // Encrypt all email contents with the symmetric key.
- if (email.MessageHtml is not null)
- {
- email.MessageHtml = Encryption.SymmetricDecrypt(email.MessageHtml, symmetricKey);
- }
-
- if (email.MessagePlain is not null)
- {
- email.MessagePlain = Encryption.SymmetricDecrypt(email.MessagePlain, symmetricKey);
- }
-
- if (email.MessagePreview is not null)
- {
- email.MessagePreview = Encryption.SymmetricDecrypt(email.MessagePreview, symmetricKey);
- }
-
- if (email.MessageSource is not null)
- {
- email.MessageSource = Encryption.SymmetricDecrypt(email.MessageSource, symmetricKey);
- }
-
- if (email.MessageSourceBytes is not null)
- {
- // Note: the decrypted bytes are the gzip-compressed source; callers must gunzip to get the raw MIME.
- email.MessageSourceBytes = Encryption.SymmetricDecrypt(email.MessageSourceBytes, symmetricKey);
- }
-
- email.Subject = Encryption.SymmetricDecrypt(email.Subject, symmetricKey);
- email.From = Encryption.SymmetricDecrypt(email.From, symmetricKey);
- email.FromLocal = Encryption.SymmetricDecrypt(email.FromLocal, symmetricKey);
- email.FromDomain = Encryption.SymmetricDecrypt(email.FromDomain, symmetricKey);
-
- // Decrypt the attachment bodies that were detached from the source.
- foreach (var part in email.Parts)
- {
- part.Bytes = Encryption.SymmetricDecrypt(part.Bytes, symmetricKey);
- }
-
- return email;
- }
}
diff --git a/apps/server/Utilities/AliasVault.Cryptography/Encryption.cs b/apps/server/Utilities/AliasVault.Cryptography/Encryption.cs
index 59f94e54d..e67daa401 100644
--- a/apps/server/Utilities/AliasVault.Cryptography/Encryption.cs
+++ b/apps/server/Utilities/AliasVault.Cryptography/Encryption.cs
@@ -7,6 +7,7 @@
namespace AliasVault.Cryptography;
+using System.Buffers.Text;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
@@ -54,23 +55,6 @@ public static class Encryption
}
}
- /// <summary>
- /// Decrypts an encrypted symmetric key using an RSA private key.
- /// </summary>
- /// <param name="ciphertext">The encrypted symmetric key as ciphertext.</param>
- /// <param name="privateKey">The RSA private key in JWK format.</param>
- /// <returns>The encrypted symmetric key as a base64-encoded string.</returns>
- public static byte[] DecryptSymmetricKeyWithRsa(string ciphertext, string privateKey)
- {
- using var rsa = RSA.Create();
-
- ImportPrivateKey(rsa, privateKey);
- var rsaParams = RSAEncryptionPadding.OaepSHA256;
-
- byte[] cipherBytes = Convert.FromBase64String(ciphertext);
- return 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>
@@ -87,23 +71,6 @@ public static class Encryption
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>
@@ -186,7 +153,7 @@ public static class Encryption
/// </summary>
/// <param name="label">The OAEP label.</param>
/// <returns>The OAEP encoding, not yet initialized.</returns>
- private static OaepEncoding LabelledOaep(string label)
+ internal static OaepEncoding LabelledOaep(string label)
{
return new OaepEncoding(new RsaBlindedEngine(), new Sha256Digest(), new Sha256Digest(), Encoding.UTF8.GetBytes(label));
}
@@ -197,78 +164,38 @@ public static class Encryption
/// <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)
+ internal static Org.BouncyCastle.Math.BigInteger JwkInteger(JsonElement jwk, string name)
{
- return new Org.BouncyCastle.Math.BigInteger(1, Base64UrlDecode(jwk.GetProperty(name).GetString()!));
+ return new Org.BouncyCastle.Math.BigInteger(1, JwkBytes(jwk.GetProperty(name).GetString()!));
}
/// <summary>
- /// Imports a public key from JWK format into an RSA provider.
+ /// Decodes a JWK field: base64url, also accepting the standard alphabet and padding that some older stored keys carry.
/// </summary>
- /// <param name="rsa">The RSA provider to import the key into.</param>
- /// <param name="jwk">The public key in JWK format.</param>
- private static void ImportPublicKey(RSA rsa, string jwk)
+ /// <param name="value">The JWK field value.</param>
+ /// <returns>The decoded bytes.</returns>
+ private static byte[] JwkBytes(string value)
{
- var jwkObj = JsonSerializer.Deserialize<JsonElement>(jwk);
- var n = Base64UrlDecode(jwkObj.GetProperty("n").GetString()!);
- var e = Base64UrlDecode(jwkObj.GetProperty("e").GetString()!);
-
- var rsaParameters = new RSAParameters
- {
- Modulus = n,
- Exponent = e,
- };
-
- rsa.ImportParameters(rsaParameters);
+ return Base64Url.DecodeFromChars(value.Replace('+', '-').Replace('/', '_').TrimEnd('='));
}
/// <summary>
- /// Imports a private key from JWK format into an RSA provider.
+ /// Imports a public key from JWK format into an RSA provider.
/// </summary>
/// <param name="rsa">The RSA provider to import the key into.</param>
- /// <param name="jwk">The private key in JWK format.</param>
- private static void ImportPrivateKey(RSA rsa, string jwk)
+ /// <param name="jwk">The public key in JWK format.</param>
+ private static void ImportPublicKey(RSA rsa, string jwk)
{
var jwkObj = JsonSerializer.Deserialize<JsonElement>(jwk);
- var n = Base64UrlDecode(jwkObj.GetProperty("n").GetString()!);
- var e = Base64UrlDecode(jwkObj.GetProperty("e").GetString()!);
- var d = Base64UrlDecode(jwkObj.GetProperty("d").GetString()!);
- var p = Base64UrlDecode(jwkObj.GetProperty("p").GetString()!);
- var q = Base64UrlDecode(jwkObj.GetProperty("q").GetString()!);
- var dp = Base64UrlDecode(jwkObj.GetProperty("dp").GetString()!);
- var dq = Base64UrlDecode(jwkObj.GetProperty("dq").GetString()!);
- var qi = Base64UrlDecode(jwkObj.GetProperty("qi").GetString()!);
+ var n = JwkBytes(jwkObj.GetProperty("n").GetString()!);
+ var e = JwkBytes(jwkObj.GetProperty("e").GetString()!);
var rsaParameters = new RSAParameters
{
Modulus = n,
Exponent = e,
- D = d,
- P = p,
- Q = q,
- DP = dp,
- DQ = dq,
- InverseQ = qi,
};
rsa.ImportParameters(rsaParameters);
}
-
- /// <summary>
- /// Decodes a Base64Url-encoded string to a byte array.
- /// </summary>
- /// <param name="base64Url">The Base64Url-encoded string.</param>
- /// <returns>The decoded byte array.</returns>
- private static byte[] Base64UrlDecode(string base64Url)
- {
- string padded = base64Url;
- switch (base64Url.Length % 4)
- {
- case 2: padded += "=="; break;
- case 3: padded += "="; break;
- }
-
- string base64 = padded.Replace("-", "+").Replace("_", "/");
- return Convert.FromBase64String(base64);
- }
}
diff --git a/apps/server/Utilities/AliasVault.Cryptography/Signing.cs b/apps/server/Utilities/AliasVault.Cryptography/Signing.cs
index ec1988282..2424bd524 100644
--- a/apps/server/Utilities/AliasVault.Cryptography/Signing.cs
+++ b/apps/server/Utilities/AliasVault.Cryptography/Signing.cs
@@ -99,17 +99,6 @@ public static class Signing
return SignedMessage(DeliveryKeyLabel, Utf8(manifestId.ToString()), Utf8(publicKey), Utf8(currentRevision.ToString(System.Globalization.CultureInfo.InvariantCulture)));
}
- /// <summary>
- /// Whether a value is a base64 Ed25519 public key.
- /// </summary>
- /// <param name="publicKeyBase64">The value to check.</param>
- /// <returns>True when it decodes to a valid public key.</returns>
- public static bool IsValidPublicKey(string? publicKeyBase64)
- {
- var bytes = TryDecode(publicKeyBase64, Ed25519.PublicKeySize);
- return bytes != null && Ed25519.ValidatePublicKeyFull(bytes, 0);
- }
-
/// <summary>
/// Whether a base64 signature over a message verifies under a base64 Ed25519 public key.
/// </summary>