mirror of
https://github.com/RedWizardsLab/EchoHub.git
synced 2026-09-04 08:36:11 +02:00
feat: Implement message encryption and decryption support
- Added IMessageEncryptionService and its implementation MessageEncryptionService for handling message encryption. - Updated ChannelsController and ChatService to encrypt messages before storing and sending. - Introduced encryption key retrieval endpoint in ServerController. - Modified EchoHubDbContext to accommodate increased message content and embed JSON lengths for encrypted data. - Created migrations to support encryption-related database changes. - Enhanced FirstRunSetup to ensure encryption key is generated if not present. - Updated appsettings.example.json to include encryption configuration. - Added comprehensive unit tests for encryption service and compatibility tests between client and server encryption.
This commit is contained in:
@@ -25,6 +25,7 @@ public sealed class AppOrchestrator : IDisposable
|
||||
|
||||
private EchoHubConnection? _connection;
|
||||
private ApiClient? _apiClient;
|
||||
private readonly ClientEncryptionService _encryption = new();
|
||||
private ClientConfig _config;
|
||||
private UserStatus _currentStatus = UserStatus.Online;
|
||||
private string? _currentStatusMessage;
|
||||
@@ -382,6 +383,19 @@ public sealed class AppOrchestrator : IDisposable
|
||||
|
||||
_currentUsername = loginResponse.Username;
|
||||
|
||||
// Fetch encryption key for E2E message encryption
|
||||
InvokeUI(() => _mainWindow.UpdateStatusBar("Fetching encryption key..."));
|
||||
try
|
||||
{
|
||||
var encryptionKey = await _apiClient.GetEncryptionKeyAsync();
|
||||
_encryption.SetKey(encryptionKey);
|
||||
Log.Information("E2E encryption key established");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log.Warning(ex, "Failed to fetch encryption key — messages will not be encrypted");
|
||||
}
|
||||
|
||||
InvokeUI(() =>
|
||||
{
|
||||
_mainWindow.SetCurrentUser(loginResponse.DisplayName ?? loginResponse.Username);
|
||||
@@ -391,7 +405,7 @@ public sealed class AppOrchestrator : IDisposable
|
||||
if (_connection is not null)
|
||||
await _connection.DisposeAsync();
|
||||
|
||||
_connection = new EchoHubConnection(result.ServerUrl, _apiClient);
|
||||
_connection = new EchoHubConnection(result.ServerUrl, _apiClient, _encryption);
|
||||
WireConnectionEvents(_connection);
|
||||
await _connection.ConnectAsync();
|
||||
|
||||
|
||||
@@ -128,6 +128,16 @@ public sealed class ApiClient : IDisposable
|
||||
return info;
|
||||
}
|
||||
|
||||
public async Task<string> GetEncryptionKeyAsync()
|
||||
{
|
||||
EnsureAuthenticated();
|
||||
var response = await AuthenticatedGetAsync("/api/server/encryption-key");
|
||||
await EnsureSuccessAsync(response);
|
||||
var result = await response.Content.ReadFromJsonAsync<EncryptionKeyResponse>()
|
||||
?? throw new InvalidOperationException("Server returned empty encryption key response.");
|
||||
return result.Key;
|
||||
}
|
||||
|
||||
public async Task<UserProfileDto?> GetUserProfileAsync(string username)
|
||||
{
|
||||
EnsureAuthenticated();
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using EchoHub.Core.Contracts;
|
||||
|
||||
namespace EchoHub.Client.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Client-side encryption service. Uses the same AES-256-GCM format as the server
|
||||
/// so messages are encrypted end-to-end between client and server.
|
||||
/// </summary>
|
||||
public sealed class ClientEncryptionService : IMessageEncryptionService
|
||||
{
|
||||
private const string EncryptionPrefix = "$ENC$v1$";
|
||||
private const int NonceSizeBytes = 12;
|
||||
private const int TagSizeBytes = 16;
|
||||
|
||||
private byte[]? _key;
|
||||
|
||||
public bool IsInitialized => _key is not null;
|
||||
public bool EncryptDatabaseEnabled => false; // Not relevant for client
|
||||
|
||||
/// <summary>
|
||||
/// Initialize with the server's encryption key (fetched after login).
|
||||
/// </summary>
|
||||
public void SetKey(string base64Key)
|
||||
{
|
||||
_key = Convert.FromBase64String(base64Key);
|
||||
|
||||
if (_key.Length != 32)
|
||||
throw new InvalidOperationException($"Encryption key must be exactly 32 bytes (256-bit). Got {_key.Length} bytes.");
|
||||
}
|
||||
|
||||
public string Encrypt(string plaintext)
|
||||
{
|
||||
if (_key is null)
|
||||
return plaintext; // Not initialized — pass through
|
||||
|
||||
var plaintextBytes = Encoding.UTF8.GetBytes(plaintext);
|
||||
var nonce = RandomNumberGenerator.GetBytes(NonceSizeBytes);
|
||||
var ciphertext = new byte[plaintextBytes.Length];
|
||||
var tag = new byte[TagSizeBytes];
|
||||
|
||||
using var aes = new AesGcm(_key, TagSizeBytes);
|
||||
aes.Encrypt(nonce, plaintextBytes, ciphertext, tag);
|
||||
|
||||
var combined = new byte[ciphertext.Length + tag.Length];
|
||||
Buffer.BlockCopy(ciphertext, 0, combined, 0, ciphertext.Length);
|
||||
Buffer.BlockCopy(tag, 0, combined, ciphertext.Length, tag.Length);
|
||||
|
||||
return $"{EncryptionPrefix}{Convert.ToBase64String(nonce)}${Convert.ToBase64String(combined)}";
|
||||
}
|
||||
|
||||
public string Decrypt(string content)
|
||||
{
|
||||
if (_key is null || !content.StartsWith(EncryptionPrefix))
|
||||
return content; // Not initialized or legacy plaintext
|
||||
|
||||
try
|
||||
{
|
||||
var payload = content[EncryptionPrefix.Length..];
|
||||
var separatorIndex = payload.IndexOf('$');
|
||||
if (separatorIndex < 0)
|
||||
return content;
|
||||
|
||||
var nonceBase64 = payload[..separatorIndex];
|
||||
var combinedBase64 = payload[(separatorIndex + 1)..];
|
||||
|
||||
var nonce = Convert.FromBase64String(nonceBase64);
|
||||
var combined = Convert.FromBase64String(combinedBase64);
|
||||
|
||||
if (combined.Length < TagSizeBytes)
|
||||
return content;
|
||||
|
||||
var ciphertextLength = combined.Length - TagSizeBytes;
|
||||
var ciphertext = combined.AsSpan(0, ciphertextLength);
|
||||
var tag = combined.AsSpan(ciphertextLength, TagSizeBytes);
|
||||
var plaintext = new byte[ciphertextLength];
|
||||
|
||||
using var aes = new AesGcm(_key, TagSizeBytes);
|
||||
aes.Decrypt(nonce, ciphertext, tag, plaintext);
|
||||
|
||||
return Encoding.UTF8.GetString(plaintext);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return "[encrypted message — decryption failed, try re-logging to fetch the latest key]";
|
||||
}
|
||||
}
|
||||
|
||||
public string? EncryptNullable(string? value)
|
||||
=> value is null ? null : Encrypt(value);
|
||||
|
||||
public string? DecryptNullable(string? value)
|
||||
=> value is null ? null : Decrypt(value);
|
||||
}
|
||||
@@ -8,6 +8,7 @@ namespace EchoHub.Client.Services;
|
||||
public sealed class EchoHubConnection : IAsyncDisposable
|
||||
{
|
||||
private readonly HubConnection _connection;
|
||||
private readonly ClientEncryptionService _encryption;
|
||||
|
||||
public event Action<MessageDto>? OnMessageReceived;
|
||||
public event Action<string, string>? OnUserJoined;
|
||||
@@ -25,8 +26,9 @@ public sealed class EchoHubConnection : IAsyncDisposable
|
||||
|
||||
public bool IsConnected => _connection.State == HubConnectionState.Connected;
|
||||
|
||||
public EchoHubConnection(string serverUrl, ApiClient apiClient)
|
||||
public EchoHubConnection(string serverUrl, ApiClient apiClient, ClientEncryptionService encryption)
|
||||
{
|
||||
_encryption = encryption;
|
||||
var hubUrl = serverUrl.TrimEnd('/') + HubConstants.ChatHubPath;
|
||||
|
||||
_connection = new HubConnectionBuilder()
|
||||
@@ -63,7 +65,9 @@ public sealed class EchoHubConnection : IAsyncDisposable
|
||||
{
|
||||
_connection.On<MessageDto>(nameof(Core.Contracts.IEchoHubClient.ReceiveMessage), message =>
|
||||
{
|
||||
OnMessageReceived?.Invoke(message);
|
||||
// Decrypt message content received from server
|
||||
var decrypted = message with { Content = _encryption.Decrypt(message.Content) };
|
||||
OnMessageReceived?.Invoke(decrypted);
|
||||
});
|
||||
|
||||
_connection.On<string, string>(nameof(Core.Contracts.IEchoHubClient.UserJoined), (channelName, username) =>
|
||||
@@ -132,7 +136,8 @@ public sealed class EchoHubConnection : IAsyncDisposable
|
||||
|
||||
public async Task<List<MessageDto>> JoinChannelAsync(string channelName)
|
||||
{
|
||||
return await _connection.InvokeAsync<List<MessageDto>>("JoinChannel", channelName);
|
||||
var messages = await _connection.InvokeAsync<List<MessageDto>>("JoinChannel", channelName);
|
||||
return DecryptMessages(messages);
|
||||
}
|
||||
|
||||
public async Task LeaveChannelAsync(string channelName)
|
||||
@@ -142,12 +147,15 @@ public sealed class EchoHubConnection : IAsyncDisposable
|
||||
|
||||
public async Task SendMessageAsync(string channelName, string content)
|
||||
{
|
||||
await _connection.InvokeAsync("SendMessage", channelName, content);
|
||||
// Encrypt content before sending to server
|
||||
var encrypted = _encryption.Encrypt(content);
|
||||
await _connection.InvokeAsync("SendMessage", channelName, encrypted);
|
||||
}
|
||||
|
||||
public async Task<List<MessageDto>> GetHistoryAsync(string channelName, int count = HubConstants.DefaultHistoryCount)
|
||||
{
|
||||
return await _connection.InvokeAsync<List<MessageDto>>("GetChannelHistory", channelName, count);
|
||||
var messages = await _connection.InvokeAsync<List<MessageDto>>("GetChannelHistory", channelName, count);
|
||||
return DecryptMessages(messages);
|
||||
}
|
||||
|
||||
public async Task UpdateStatusAsync(UserStatus status, string? statusMessage = null)
|
||||
@@ -160,6 +168,11 @@ public sealed class EchoHubConnection : IAsyncDisposable
|
||||
return await _connection.InvokeAsync<List<UserPresenceDto>>("GetOnlineUsers", channelName);
|
||||
}
|
||||
|
||||
private List<MessageDto> DecryptMessages(List<MessageDto> messages)
|
||||
{
|
||||
return messages.Select(m => m with { Content = _encryption.Decrypt(m.Content) }).ToList();
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
await _connection.DisposeAsync();
|
||||
|
||||
Reference in New Issue
Block a user