├── EncryptedChat ├── EncryptedChat.Server.Web │ ├── appsettings.json │ ├── appsettings.Development.json │ ├── EncryptedChat.Server.Web.csproj │ ├── Constants.cs │ ├── Models │ │ ├── ClientUser.cs │ │ └── User.cs │ ├── Program.cs │ ├── Services │ │ ├── IChatService.cs │ │ └── Implementations │ │ │ └── ChatService.cs │ ├── Startup.cs │ └── Hubs │ │ └── ChatHub.cs ├── EncryptedChat.Client.App │ ├── State.cs │ ├── Commands.cs │ ├── Program.cs │ ├── EncryptedChat.Client.App.csproj │ ├── Messages.cs │ └── Engine.cs ├── EncryptedChat.Client.Common │ ├── Models │ │ └── User.cs │ ├── EncryptedChat.Client.Common.csproj │ ├── Constants.cs │ ├── Configuration │ │ ├── MainConfiguration.cs │ │ └── ConfigurationManager.cs │ └── Crypto │ │ ├── HashingUtil.cs │ │ ├── EncryptedCommunicationsManager.cs │ │ ├── AesCryptographyManager.cs │ │ └── RsaCryptographyManager.cs └── EncryptedChat.sln ├── README.md ├── LICENSE └── .gitignore /EncryptedChat/EncryptedChat.Server.Web/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Warning" 5 | } 6 | }, 7 | "AllowedHosts": "*" 8 | } 9 | -------------------------------------------------------------------------------- /EncryptedChat/EncryptedChat.Client.App/State.cs: -------------------------------------------------------------------------------- 1 | namespace EncryptedChat.Client.App 2 | { 3 | public enum State 4 | { 5 | SelectingUser, 6 | Waiting, 7 | InChat, 8 | Disconnected 9 | } 10 | } -------------------------------------------------------------------------------- /EncryptedChat/EncryptedChat.Server.Web/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Debug", 5 | "System": "Information", 6 | "Microsoft": "Information" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /EncryptedChat/EncryptedChat.Client.App/Commands.cs: -------------------------------------------------------------------------------- 1 | namespace EncryptedChat.Client.App 2 | { 3 | public static class Commands 4 | { 5 | public const string ExitCommand = "/e"; 6 | public const string TrustCommand = "/trust"; 7 | } 8 | } -------------------------------------------------------------------------------- /EncryptedChat/EncryptedChat.Server.Web/EncryptedChat.Server.Web.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.1 5 | full 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /EncryptedChat/EncryptedChat.Client.Common/Models/User.cs: -------------------------------------------------------------------------------- 1 | namespace EncryptedChat.Client.Common.Models 2 | { 3 | public class User 4 | { 5 | public string Id { get; set; } 6 | 7 | public string Username { get; set; } 8 | 9 | public string PublicKey { get; set; } 10 | } 11 | } -------------------------------------------------------------------------------- /EncryptedChat/EncryptedChat.Client.App/Program.cs: -------------------------------------------------------------------------------- 1 | namespace EncryptedChat.Client.App 2 | { 3 | public static class Program 4 | { 5 | public static void Main() 6 | { 7 | var engine = new Engine(); 8 | 9 | engine.Setup().GetAwaiter().GetResult(); 10 | } 11 | } 12 | } -------------------------------------------------------------------------------- /EncryptedChat/EncryptedChat.Server.Web/Constants.cs: -------------------------------------------------------------------------------- 1 | namespace EncryptedChat.Server.Web 2 | { 3 | public static class Constants 4 | { 5 | public const string RedirectUrl = "https://github.com/martinmladenov/encrypted-chat"; 6 | public const string UsernameRegex = @"^(?=.{3,20}$)(?![_.])(?!.*[_.]{2})[a-zA-Z0-9._]+(? 2 | 3 | 4 | netcoreapp3.1 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /EncryptedChat/EncryptedChat.Server.Web/Models/ClientUser.cs: -------------------------------------------------------------------------------- 1 | namespace EncryptedChat.Server.Web.Models 2 | { 3 | public class ClientUser 4 | { 5 | public string Id { get; set; } 6 | 7 | // For backward compatibility 8 | public string ConnectionId => this.Id; 9 | 10 | public string Username { get; set; } 11 | 12 | public string PublicKey { get; set; } 13 | } 14 | } -------------------------------------------------------------------------------- /EncryptedChat/EncryptedChat.Client.Common/Constants.cs: -------------------------------------------------------------------------------- 1 | namespace EncryptedChat.Client.Common 2 | { 3 | public static class Constants 4 | { 5 | public const string ConfigurationFilePath = "encrypted-chat-config.json"; 6 | public const string DefaultServerUrl = "https://ench.azurewebsites.net/chat"; 7 | public const string UsernameRegex = @"^(?=.{3,20}$)(?![_.])(?!.*[_.]{2})[a-zA-Z0-9._]+(? 14 | WebHost.CreateDefaultBuilder(args) 15 | .UseStartup(); 16 | } 17 | } -------------------------------------------------------------------------------- /EncryptedChat/EncryptedChat.Client.Common/Configuration/MainConfiguration.cs: -------------------------------------------------------------------------------- 1 | namespace EncryptedChat.Client.Common.Configuration 2 | { 3 | using System.Collections.Generic; 4 | 5 | public class MainConfiguration 6 | { 7 | public string Username { get; set; } 8 | 9 | public string ServerUrl { get; set; } = Constants.DefaultServerUrl; 10 | 11 | public string PrivateKey { get; set; } 12 | 13 | public IDictionary TrustedUsers { get; set; } 14 | = new Dictionary(); 15 | } 16 | } -------------------------------------------------------------------------------- /EncryptedChat/EncryptedChat.Client.App/EncryptedChat.Client.App.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | netcoreapp3.1 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # encrypted-chat 2 | 3 | Secure end-to-end encrypted chat client and server using SignalR 4 | 5 | ### Build status 6 | | Client | Server 7 | |---|--- 8 | | [![Build Status](https://dev.azure.com/martinml/EncryptedChat/_apis/build/status/Build%20client?branchName=master)](https://dev.azure.com/martinml/EncryptedChat/_build/latest?definitionId=8&branchName=master) | [![Build Status](https://dev.azure.com/martinml/EncryptedChat/_apis/build/status/EncryptedChat-ASP.NET%20Core-CI?branchName=master)](https://dev.azure.com/martinml/EncryptedChat/_build/latest?definitionId=6&branchName=master) 9 | -------------------------------------------------------------------------------- /EncryptedChat/EncryptedChat.Server.Web/Services/IChatService.cs: -------------------------------------------------------------------------------- 1 | namespace EncryptedChat.Server.Web.Services 2 | { 3 | using Models; 4 | 5 | public interface IChatService 6 | { 7 | bool AddWaitingUser(string connectionId, string username, string publicKey); 8 | 9 | User[] GetWaitingUsers(); 10 | 11 | string SetupConnectionToUser(string currUsername, string otherId, string currConnectionId, 12 | string key); 13 | 14 | User GetUserByConnectionId(string connectionId); 15 | 16 | string RemoveUserByConnectionId(string connectionId); 17 | 18 | bool IsWaiting(string connectionId); 19 | } 20 | } -------------------------------------------------------------------------------- /EncryptedChat/EncryptedChat.Server.Web/Models/User.cs: -------------------------------------------------------------------------------- 1 | namespace EncryptedChat.Server.Web.Models 2 | { 3 | public class User 4 | { 5 | public string Id { get; set; } 6 | 7 | public string ConnectionId { get; set; } 8 | 9 | public string Username { get; set; } 10 | 11 | public string OtherUserConnectionId { get; set; } 12 | 13 | public string PublicKey { get; set; } 14 | 15 | public ClientUser ToClientUser() 16 | { 17 | return new ClientUser 18 | { 19 | Id = this.Id, 20 | Username = this.Username, 21 | PublicKey = this.PublicKey 22 | }; 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /EncryptedChat/EncryptedChat.Client.Common/Crypto/HashingUtil.cs: -------------------------------------------------------------------------------- 1 | namespace EncryptedChat.Client.Common.Crypto 2 | { 3 | using System.Security.Cryptography; 4 | using System.Text; 5 | 6 | public static class HashingUtil 7 | { 8 | public static string GetSha256Hash(string str) 9 | { 10 | byte[] hashBytes; 11 | using (SHA256 sha256 = new SHA256Managed()) 12 | { 13 | hashBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(str)); 14 | } 15 | 16 | var sb = new StringBuilder(64); 17 | foreach (byte b in hashBytes) 18 | { 19 | sb.Append(b.ToString("X2")); 20 | } 21 | 22 | return sb.ToString(); 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Martin Mladenov 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /EncryptedChat/EncryptedChat.Client.Common/Configuration/ConfigurationManager.cs: -------------------------------------------------------------------------------- 1 | namespace EncryptedChat.Client.Common.Configuration 2 | { 3 | using System.IO; 4 | using Newtonsoft.Json; 5 | 6 | public class ConfigurationManager 7 | where T : new() 8 | { 9 | private readonly string configFilePath; 10 | 11 | public ConfigurationManager(string configFilePath) 12 | { 13 | this.configFilePath = configFilePath; 14 | 15 | this.ReloadConfiguration(); 16 | } 17 | 18 | public T Configuration { get; private set; } 19 | 20 | public void ReloadConfiguration() 21 | { 22 | if (!File.Exists(this.configFilePath)) 23 | { 24 | this.Configuration = new T(); 25 | this.SaveChanges(); 26 | return; 27 | } 28 | 29 | string configJson = File.ReadAllText(this.configFilePath); 30 | 31 | this.Configuration = JsonConvert.DeserializeObject(configJson); 32 | } 33 | 34 | public void SaveChanges() 35 | { 36 | string newConfigJson = JsonConvert.SerializeObject(this.Configuration); 37 | 38 | File.WriteAllText(this.configFilePath, newConfigJson); 39 | } 40 | } 41 | } -------------------------------------------------------------------------------- /EncryptedChat/EncryptedChat.Server.Web/Startup.cs: -------------------------------------------------------------------------------- 1 | namespace EncryptedChat.Server.Web 2 | { 3 | using System.Threading.Tasks; 4 | using Hubs; 5 | using Microsoft.AspNetCore.Builder; 6 | using Microsoft.AspNetCore.Hosting; 7 | using Microsoft.Extensions.Configuration; 8 | using Microsoft.Extensions.DependencyInjection; 9 | using Microsoft.Extensions.Hosting; 10 | using Services; 11 | using Services.Implementations; 12 | 13 | public class Startup 14 | { 15 | public Startup(IConfiguration configuration) 16 | { 17 | this.Configuration = configuration; 18 | } 19 | 20 | private IConfiguration Configuration { get; } 21 | 22 | public void ConfigureServices(IServiceCollection services) 23 | { 24 | services.AddSignalR(); 25 | 26 | services.AddSingleton(); 27 | } 28 | 29 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 30 | { 31 | if (env.IsDevelopment()) 32 | { 33 | app.UseDeveloperExceptionPage(); 34 | } 35 | else 36 | { 37 | app.UseExceptionHandler("/Error"); 38 | app.UseHsts(); 39 | } 40 | 41 | app.UseHttpsRedirection(); 42 | 43 | app.UseRouting(); 44 | 45 | app.UseEndpoints(endpoints => { endpoints.MapHub("/chat"); }); 46 | 47 | app.Run(context => 48 | { 49 | context.Response.Redirect(Constants.RedirectUrl); 50 | return Task.FromResult(null); 51 | }); 52 | } 53 | } 54 | } -------------------------------------------------------------------------------- /EncryptedChat/EncryptedChat.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Client", "Client", "{AD611021-925E-47F5-A17C-2A60D1E30EC5}" 4 | EndProject 5 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Server", "Server", "{C90B20E3-F393-4949-8590-E482A254E6DD}" 6 | EndProject 7 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EncryptedChat.Client.Common", "EncryptedChat.Client.Common\EncryptedChat.Client.Common.csproj", "{269D0648-0AE7-4BB8-8667-33DA7572EB59}" 8 | EndProject 9 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EncryptedChat.Client.App", "EncryptedChat.Client.App\EncryptedChat.Client.App.csproj", "{49A1A5D9-8548-46E8-BDBA-DDB1B730FA50}" 10 | EndProject 11 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EncryptedChat.Server.Web", "EncryptedChat.Server.Web\EncryptedChat.Server.Web.csproj", "{F8DA51D2-4560-4E94-B7CC-20A20E504492}" 12 | EndProject 13 | Global 14 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 15 | Debug|Any CPU = Debug|Any CPU 16 | Release|Any CPU = Release|Any CPU 17 | EndGlobalSection 18 | GlobalSection(NestedProjects) = preSolution 19 | {269D0648-0AE7-4BB8-8667-33DA7572EB59} = {AD611021-925E-47F5-A17C-2A60D1E30EC5} 20 | {49A1A5D9-8548-46E8-BDBA-DDB1B730FA50} = {AD611021-925E-47F5-A17C-2A60D1E30EC5} 21 | {F8DA51D2-4560-4E94-B7CC-20A20E504492} = {C90B20E3-F393-4949-8590-E482A254E6DD} 22 | EndGlobalSection 23 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 24 | {269D0648-0AE7-4BB8-8667-33DA7572EB59}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 25 | {269D0648-0AE7-4BB8-8667-33DA7572EB59}.Debug|Any CPU.Build.0 = Debug|Any CPU 26 | {269D0648-0AE7-4BB8-8667-33DA7572EB59}.Release|Any CPU.ActiveCfg = Release|Any CPU 27 | {269D0648-0AE7-4BB8-8667-33DA7572EB59}.Release|Any CPU.Build.0 = Release|Any CPU 28 | {49A1A5D9-8548-46E8-BDBA-DDB1B730FA50}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 29 | {49A1A5D9-8548-46E8-BDBA-DDB1B730FA50}.Debug|Any CPU.Build.0 = Debug|Any CPU 30 | {49A1A5D9-8548-46E8-BDBA-DDB1B730FA50}.Release|Any CPU.ActiveCfg = Release|Any CPU 31 | {49A1A5D9-8548-46E8-BDBA-DDB1B730FA50}.Release|Any CPU.Build.0 = Release|Any CPU 32 | {F8DA51D2-4560-4E94-B7CC-20A20E504492}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 33 | {F8DA51D2-4560-4E94-B7CC-20A20E504492}.Debug|Any CPU.Build.0 = Debug|Any CPU 34 | {F8DA51D2-4560-4E94-B7CC-20A20E504492}.Release|Any CPU.ActiveCfg = Release|Any CPU 35 | {F8DA51D2-4560-4E94-B7CC-20A20E504492}.Release|Any CPU.Build.0 = Release|Any CPU 36 | EndGlobalSection 37 | EndGlobal 38 | -------------------------------------------------------------------------------- /EncryptedChat/EncryptedChat.Client.Common/Crypto/EncryptedCommunicationsManager.cs: -------------------------------------------------------------------------------- 1 | namespace EncryptedChat.Client.Common.Crypto 2 | { 3 | public class EncryptedCommunicationsManager 4 | { 5 | private const char Delimiter = '-'; 6 | 7 | private readonly RsaCryptographyManager otherRsa; 8 | private readonly RsaCryptographyManager ownRsa; 9 | private readonly AesCryptographyManager aes; 10 | 11 | public EncryptedCommunicationsManager() 12 | { 13 | this.otherRsa = new RsaCryptographyManager(); 14 | this.ownRsa = new RsaCryptographyManager(); 15 | this.aes = new AesCryptographyManager(); 16 | } 17 | 18 | public string EncryptMessage(string message) 19 | { 20 | var iv = this.aes.ResetIv(); 21 | var encrypted = this.aes.Encrypt(message); 22 | 23 | var encryptedData = iv + Delimiter + encrypted; 24 | 25 | return encryptedData; 26 | } 27 | 28 | public string DecryptMessage(string encryptedData) 29 | { 30 | var data = encryptedData.Split(Delimiter); 31 | var iv = data[0]; 32 | var encryptedMessage = data[1]; 33 | 34 | var decrypted = this.aes.Decrypt(encryptedMessage, iv); 35 | 36 | return decrypted; 37 | } 38 | 39 | public void GenerateNewRsaKey() => this.ownRsa.GenerateNewKey(); 40 | 41 | public string ExportOwnRsaKey(bool includePrivate = false) 42 | => this.ownRsa.ExportKeyAsXml(includePrivate); 43 | 44 | public void ImportOwnRsaKey(string key) 45 | { 46 | this.ownRsa.LoadKeyFromXml(key); 47 | } 48 | 49 | public void ImportOtherRsaKey(string key) 50 | { 51 | this.otherRsa.LoadKeyFromXml(key); 52 | } 53 | 54 | public string GenerateEncryptedAesKey() 55 | { 56 | var aesKey = this.aes.GenerateKey(); 57 | var encryptedKey = this.otherRsa.EncryptData(aesKey); 58 | return encryptedKey; 59 | } 60 | 61 | public string SignData(string data) 62 | => this.ownRsa.SignData(data); 63 | 64 | public bool VerifySignature(string data, string signature) 65 | => this.otherRsa.VerifySignature(data, signature); 66 | 67 | public void ImportEncryptedAesKey(string key) 68 | { 69 | var aes1KeyDec = this.ownRsa.DecryptDataAsByteArray(key); 70 | this.aes.LoadKey(aes1KeyDec); 71 | } 72 | 73 | public string GetOwnRsaFingerprint() => this.ownRsa.GetSha256Fingerprint(); 74 | 75 | public string GetOtherRsaFingerprint() => this.otherRsa.GetSha256Fingerprint(); 76 | } 77 | } -------------------------------------------------------------------------------- /EncryptedChat/EncryptedChat.Client.App/Messages.cs: -------------------------------------------------------------------------------- 1 | namespace EncryptedChat.Client.App 2 | { 3 | public static class Messages 4 | { 5 | public const string ConnectingToServer = "Connecting to {0}..."; 6 | public const string Connected = "Connected."; 7 | public const string Disconnected = "Disconnected."; 8 | public const string UsernamePrompt = "Username: "; 9 | public const string InvalidUserIdSelectedError = "Please type a number from 0 to {0}"; 10 | public const string GeneratingSessionKey = "Generating session key..."; 11 | public const string InitialisingEncryptedConnection = "Initialising encrypted connection..."; 12 | public const string IncomingConnectionSignatureInvalid = "Could not verify user identity."; 13 | public const string OtherUsernameInvalid = "The other user's username is invalid."; 14 | public const string ConnectedWithUser = "Connected with {0} - {1}!"; 15 | public const string UserListHeader = "Users:"; 16 | public const string UserListItem = "{0} - {1} {2}"; 17 | public const string UserListInvalidUsername = "Not showing {0} user{1} with an invalid username."; 18 | public const string UserListJoin = "0 - join waiting list"; 19 | public const string UserTrustedBadge = "[trusted]"; 20 | public const string UserNotTrustedBadge = "[not trusted]"; 21 | public const string UserListNoUsers = "None"; 22 | public const string GeneratingKeyPair = "Generating keypair..."; 23 | public const string LoadingPrivateKey = "Loading private key..."; 24 | public const string SendingKeyToServer = "Sending public key to server..."; 25 | public const string WaitingForUser = "Waiting for other user"; 26 | public const string CurrentUserFingerprint = "Your fingerprint: {0}"; 27 | public const string OtherUserFingerprint = "{0}'s fingerprint: {1}"; 28 | public const string MessageFormat = "<{0}> {1}"; 29 | public const string LoadingConfiguration = "Loading configuration..."; 30 | public const string UserTrusted = "User trusted."; 31 | public const string CouldNotTrustUser = "Could not trust user"; 32 | 33 | public const string UserNotTrustedMessage = "User not trusted. Verify key fingerprints and type " 34 | + Commands.TrustCommand + " to trust user"; 35 | 36 | public const string UsernameInfo = 37 | "Please choose a username. It must be between 3 and 20 characters long and " + 38 | "may contain uppercase and lowercase letters from the English alphabet, " + 39 | "digits, dots, and underscores. It may not begin or end with " + 40 | "a dot or an underscore, or contain two or more of them in a row."; 41 | } 42 | } -------------------------------------------------------------------------------- /EncryptedChat/EncryptedChat.Server.Web/Hubs/ChatHub.cs: -------------------------------------------------------------------------------- 1 | namespace EncryptedChat.Server.Web.Hubs 2 | { 3 | using System; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | using Microsoft.AspNetCore.SignalR; 7 | using Services; 8 | 9 | public class ChatHub : Hub 10 | { 11 | private readonly IChatService chatService; 12 | 13 | public ChatHub(IChatService chatService) 14 | { 15 | this.chatService = chatService; 16 | } 17 | 18 | public async Task RegisterAsWaiting(string username, string publicKey) 19 | { 20 | bool result = this.chatService.AddWaitingUser(this.Context.ConnectionId, username, publicKey); 21 | 22 | if (!result) 23 | { 24 | this.Context.Abort(); 25 | return; 26 | } 27 | 28 | await this.UpdateClientWaitingList(); 29 | } 30 | 31 | private async Task UpdateClientWaitingList(string recipientId = null) 32 | { 33 | var freeUsers = this.chatService.GetWaitingUsers().Select(u => u.ToClientUser()).ToArray(); 34 | 35 | var recipient = recipientId == null ? this.Clients.All : this.Clients.Client(recipientId); 36 | 37 | await recipient.SendCoreAsync("UpdateWaitingList", new object[] {freeUsers}); 38 | } 39 | 40 | public async Task ConnectToUser(string username, string otherId, string aesKey, 41 | string rsaKey, string signature) 42 | { 43 | var otherConnectionId = this.chatService.SetupConnectionToUser( 44 | username, otherId, this.Context.ConnectionId, aesKey); 45 | 46 | if (otherConnectionId == null) 47 | { 48 | this.Context.Abort(); 49 | return; 50 | } 51 | 52 | await this.Clients.Client(otherConnectionId) 53 | .SendCoreAsync("AcceptConnection", new object[] {aesKey, username, rsaKey, signature}); 54 | 55 | await this.UpdateClientWaitingList(); 56 | } 57 | 58 | public async Task SendMessage(string encryptedMessage) 59 | { 60 | var user = this.chatService.GetUserByConnectionId(this.Context.ConnectionId); 61 | 62 | if (user == null || user.OtherUserConnectionId == null) 63 | { 64 | return; 65 | } 66 | 67 | await this.Clients.Client(user.OtherUserConnectionId) 68 | .SendCoreAsync("NewMessage", new object[] {encryptedMessage, user.Username}); 69 | } 70 | 71 | public override async Task OnDisconnectedAsync(Exception exception) 72 | { 73 | bool isWaiting = this.chatService.IsWaiting(this.Context.ConnectionId); 74 | 75 | var otherUserConnectionId = this.chatService.RemoveUserByConnectionId(this.Context.ConnectionId); 76 | 77 | if (otherUserConnectionId != null) 78 | { 79 | await this.Clients.Client(otherUserConnectionId).SendCoreAsync("Disconnect", new object[0]); 80 | } 81 | 82 | if (isWaiting) 83 | { 84 | await this.UpdateClientWaitingList(); 85 | } 86 | 87 | await base.OnDisconnectedAsync(exception); 88 | } 89 | 90 | public override async Task OnConnectedAsync() 91 | { 92 | await base.OnConnectedAsync(); 93 | 94 | await this.UpdateClientWaitingList(this.Context.ConnectionId); 95 | } 96 | } 97 | } -------------------------------------------------------------------------------- /EncryptedChat/EncryptedChat.Client.Common/Crypto/AesCryptographyManager.cs: -------------------------------------------------------------------------------- 1 | namespace EncryptedChat.Client.Common.Crypto 2 | { 3 | using System; 4 | using System.IO; 5 | using System.Security.Cryptography; 6 | 7 | public class AesCryptographyManager 8 | { 9 | private Aes aes; 10 | 11 | public string Encrypt(string text) 12 | { 13 | return Convert.ToBase64String(this.EncryptAsByteArray(text)); 14 | } 15 | 16 | public byte[] EncryptAsByteArray(string text) 17 | { 18 | if (string.IsNullOrEmpty(text)) 19 | { 20 | throw new ArgumentNullException(nameof(text)); 21 | } 22 | 23 | byte[] encrypted; 24 | 25 | using (var memoryStream = new MemoryStream()) 26 | using (var cryptoStream = new CryptoStream(memoryStream, 27 | this.aes.CreateEncryptor(), CryptoStreamMode.Write)) 28 | { 29 | using (var streamWriter = new StreamWriter(cryptoStream)) 30 | { 31 | streamWriter.Write(text); 32 | } 33 | 34 | encrypted = memoryStream.ToArray(); 35 | } 36 | 37 | return encrypted; 38 | } 39 | 40 | public string Decrypt(string cipherText, string iv) 41 | { 42 | if (cipherText == null) 43 | { 44 | throw new ArgumentNullException(nameof(cipherText)); 45 | } 46 | 47 | if (iv == null) 48 | { 49 | throw new ArgumentNullException(nameof(iv)); 50 | } 51 | 52 | return this.Decrypt(Convert.FromBase64String(cipherText), Convert.FromBase64String(iv)); 53 | } 54 | 55 | public string Decrypt(byte[] cipherText, byte[] iv) 56 | { 57 | if (cipherText == null) 58 | { 59 | throw new ArgumentNullException(nameof(cipherText)); 60 | } 61 | 62 | if (iv == null) 63 | { 64 | throw new ArgumentNullException(nameof(iv)); 65 | } 66 | 67 | this.aes.IV = iv; 68 | 69 | string plaintext; 70 | 71 | using (var memoryStream = new MemoryStream(cipherText)) 72 | using (var cryptoStream = new CryptoStream(memoryStream, this.aes.CreateDecryptor(), CryptoStreamMode.Read)) 73 | using (var streamReader = new StreamReader(cryptoStream)) 74 | { 75 | plaintext = streamReader.ReadToEnd(); 76 | } 77 | 78 | 79 | return plaintext; 80 | } 81 | 82 | public byte[] GenerateKey() 83 | { 84 | this.aes = Aes.Create(); 85 | 86 | return this.aes.Key; 87 | } 88 | 89 | public void LoadKey(string key) 90 | { 91 | if (key == null) 92 | { 93 | throw new ArgumentNullException(nameof(key)); 94 | } 95 | 96 | this.LoadKey(Convert.FromBase64String(key)); 97 | } 98 | 99 | public void LoadKey(byte[] key) 100 | { 101 | if (key == null) 102 | { 103 | throw new ArgumentNullException(nameof(key)); 104 | } 105 | 106 | this.aes = Aes.Create(); 107 | 108 | this.aes.Key = key; 109 | } 110 | 111 | public string ResetIv() 112 | { 113 | return Convert.ToBase64String(this.ResetIvAsByteArray()); 114 | } 115 | 116 | public byte[] ResetIvAsByteArray() 117 | { 118 | this.aes.GenerateIV(); 119 | 120 | return this.aes.IV; 121 | } 122 | } 123 | } -------------------------------------------------------------------------------- /EncryptedChat/EncryptedChat.Server.Web/Services/Implementations/ChatService.cs: -------------------------------------------------------------------------------- 1 | namespace EncryptedChat.Server.Web.Services.Implementations 2 | { 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Text.RegularExpressions; 7 | using Models; 8 | 9 | public class ChatService : IChatService 10 | { 11 | private readonly HashSet users; 12 | 13 | public ChatService() 14 | { 15 | this.users = new HashSet(); 16 | } 17 | 18 | public bool AddWaitingUser(string connectionId, string username, string publicKey) 19 | { 20 | if (string.IsNullOrWhiteSpace(username) || 21 | !Regex.IsMatch(username, Constants.UsernameRegex) || 22 | string.IsNullOrWhiteSpace(publicKey) || 23 | this.users.Any(u => u.Username == username)) 24 | { 25 | return false; 26 | } 27 | 28 | this.users.Add(new User 29 | { 30 | Id = Guid.NewGuid().ToString(), 31 | ConnectionId = connectionId, Username = username, PublicKey = publicKey 32 | }); 33 | 34 | return true; 35 | } 36 | 37 | public User[] GetWaitingUsers() 38 | { 39 | var freeUsers = this.users.Where(u => u.OtherUserConnectionId == null).ToArray(); 40 | 41 | return freeUsers; 42 | } 43 | 44 | public string SetupConnectionToUser(string currUsername, string otherId, string currConnectionId, 45 | string key) 46 | { 47 | if (string.IsNullOrWhiteSpace(currUsername) || 48 | !Regex.IsMatch(currUsername, Constants.UsernameRegex) || 49 | string.IsNullOrWhiteSpace(otherId) || 50 | string.IsNullOrWhiteSpace(currConnectionId) || 51 | string.IsNullOrWhiteSpace(key)) 52 | { 53 | return null; 54 | } 55 | 56 | var otherUser = this.users.SingleOrDefault(u => u.Id == otherId); 57 | 58 | if (otherUser == null || otherUser.OtherUserConnectionId != null) 59 | { 60 | return null; 61 | } 62 | 63 | var currUser = new User 64 | { 65 | Id = Guid.NewGuid().ToString(), 66 | ConnectionId = currConnectionId, Username = currUsername 67 | }; 68 | 69 | this.users.Add(currUser); 70 | 71 | otherUser.OtherUserConnectionId = currUser.ConnectionId; 72 | currUser.OtherUserConnectionId = otherUser.ConnectionId; 73 | 74 | return otherUser.ConnectionId; 75 | } 76 | 77 | public User GetUserByConnectionId(string connectionId) 78 | { 79 | if (connectionId == null) 80 | { 81 | return null; 82 | } 83 | 84 | return this.users.SingleOrDefault(u => u.ConnectionId == connectionId); 85 | } 86 | 87 | public bool IsWaiting(string connectionId) 88 | { 89 | var user = this.users.SingleOrDefault(u => u.ConnectionId == connectionId); 90 | 91 | if (user == null) 92 | { 93 | return false; 94 | } 95 | 96 | return user.OtherUserConnectionId == null; 97 | } 98 | 99 | public string RemoveUserByConnectionId(string connectionId) 100 | { 101 | if (connectionId == null) 102 | { 103 | return null; 104 | } 105 | 106 | var user = this.users.SingleOrDefault(u => u.ConnectionId == connectionId); 107 | 108 | if (user == null) 109 | { 110 | return null; 111 | } 112 | 113 | this.users.Remove(user); 114 | 115 | string otherConnectionId = user.OtherUserConnectionId; 116 | 117 | if (otherConnectionId == null) 118 | { 119 | return null; 120 | } 121 | 122 | var otherUser = this.users.SingleOrDefault(u => u.ConnectionId == otherConnectionId); 123 | 124 | if (otherUser != null) 125 | { 126 | this.users.Remove(otherUser); 127 | } 128 | 129 | return otherConnectionId; 130 | } 131 | } 132 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.suo 8 | *.user 9 | *.userosscache 10 | *.sln.docstates 11 | 12 | # User-specific files (MonoDevelop/Xamarin Studio) 13 | *.userprefs 14 | 15 | # Build results 16 | [Dd]ebug/ 17 | [Dd]ebugPublic/ 18 | [Rr]elease/ 19 | [Rr]eleases/ 20 | x64/ 21 | x86/ 22 | bld/ 23 | [Bb]in/ 24 | [Oo]bj/ 25 | [Ll]og/ 26 | 27 | # Visual Studio 2015/2017 cache/options directory 28 | .vs/ 29 | # Uncomment if you have tasks that create the project's static files in wwwroot 30 | #wwwroot/ 31 | 32 | # Visual Studio 2017 auto generated files 33 | Generated\ Files/ 34 | 35 | # MSTest test Results 36 | [Tt]est[Rr]esult*/ 37 | [Bb]uild[Ll]og.* 38 | 39 | # NUNIT 40 | *.VisualState.xml 41 | TestResult.xml 42 | 43 | # Build Results of an ATL Project 44 | [Dd]ebugPS/ 45 | [Rr]eleasePS/ 46 | dlldata.c 47 | 48 | # Benchmark Results 49 | BenchmarkDotNet.Artifacts/ 50 | 51 | # .NET Core 52 | project.lock.json 53 | project.fragment.lock.json 54 | artifacts/ 55 | **/Properties/launchSettings.json 56 | 57 | # StyleCop 58 | StyleCopReport.xml 59 | 60 | # Files built by Visual Studio 61 | *_i.c 62 | *_p.c 63 | *_i.h 64 | *.ilk 65 | *.meta 66 | *.obj 67 | *.iobj 68 | *.pch 69 | *.pdb 70 | *.ipdb 71 | *.pgc 72 | *.pgd 73 | *.rsp 74 | *.sbr 75 | *.tlb 76 | *.tli 77 | *.tlh 78 | *.tmp 79 | *.tmp_proj 80 | *.log 81 | *.vspscc 82 | *.vssscc 83 | .builds 84 | *.pidb 85 | *.svclog 86 | *.scc 87 | 88 | # Chutzpah Test files 89 | _Chutzpah* 90 | 91 | # Visual C++ cache files 92 | ipch/ 93 | *.aps 94 | *.ncb 95 | *.opendb 96 | *.opensdf 97 | *.sdf 98 | *.cachefile 99 | *.VC.db 100 | *.VC.VC.opendb 101 | 102 | # Visual Studio profiler 103 | *.psess 104 | *.vsp 105 | *.vspx 106 | *.sap 107 | 108 | # Visual Studio Trace Files 109 | *.e2e 110 | 111 | # TFS 2012 Local Workspace 112 | $tf/ 113 | 114 | # Guidance Automation Toolkit 115 | *.gpState 116 | 117 | # ReSharper is a .NET coding add-in 118 | _ReSharper*/ 119 | *.[Rr]e[Ss]harper 120 | *.DotSettings.user 121 | 122 | # JustCode is a .NET coding add-in 123 | .JustCode 124 | 125 | # TeamCity is a build add-in 126 | _TeamCity* 127 | 128 | # DotCover is a Code Coverage Tool 129 | *.dotCover 130 | 131 | # AxoCover is a Code Coverage Tool 132 | .axoCover/* 133 | !.axoCover/settings.json 134 | 135 | # Visual Studio code coverage results 136 | *.coverage 137 | *.coveragexml 138 | 139 | # NCrunch 140 | _NCrunch_* 141 | .*crunch*.local.xml 142 | nCrunchTemp_* 143 | 144 | # MightyMoose 145 | *.mm.* 146 | AutoTest.Net/ 147 | 148 | # Web workbench (sass) 149 | .sass-cache/ 150 | 151 | # Installshield output folder 152 | [Ee]xpress/ 153 | 154 | # DocProject is a documentation generator add-in 155 | DocProject/buildhelp/ 156 | DocProject/Help/*.HxT 157 | DocProject/Help/*.HxC 158 | DocProject/Help/*.hhc 159 | DocProject/Help/*.hhk 160 | DocProject/Help/*.hhp 161 | DocProject/Help/Html2 162 | DocProject/Help/html 163 | 164 | # Click-Once directory 165 | publish/ 166 | 167 | # Publish Web Output 168 | *.[Pp]ublish.xml 169 | *.azurePubxml 170 | # Note: Comment the next line if you want to checkin your web deploy settings, 171 | # but database connection strings (with potential passwords) will be unencrypted 172 | *.pubxml 173 | *.publishproj 174 | 175 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 176 | # checkin your Azure Web App publish settings, but sensitive information contained 177 | # in these scripts will be unencrypted 178 | PublishScripts/ 179 | 180 | # NuGet Packages 181 | *.nupkg 182 | # The packages folder can be ignored because of Package Restore 183 | **/[Pp]ackages/* 184 | # except build/, which is used as an MSBuild target. 185 | !**/[Pp]ackages/build/ 186 | # Uncomment if necessary however generally it will be regenerated when needed 187 | #!**/[Pp]ackages/repositories.config 188 | # NuGet v3's project.json files produces more ignorable files 189 | *.nuget.props 190 | *.nuget.targets 191 | 192 | # Microsoft Azure Build Output 193 | csx/ 194 | *.build.csdef 195 | 196 | # Microsoft Azure Emulator 197 | ecf/ 198 | rcf/ 199 | 200 | # Windows Store app package directories and files 201 | AppPackages/ 202 | BundleArtifacts/ 203 | Package.StoreAssociation.xml 204 | _pkginfo.txt 205 | *.appx 206 | 207 | # Visual Studio cache files 208 | # files ending in .cache can be ignored 209 | *.[Cc]ache 210 | # but keep track of directories ending in .cache 211 | !*.[Cc]ache/ 212 | 213 | # Others 214 | ClientBin/ 215 | ~$* 216 | *~ 217 | *.dbmdl 218 | *.dbproj.schemaview 219 | *.jfm 220 | *.pfx 221 | *.publishsettings 222 | orleans.codegen.cs 223 | 224 | # Including strong name files can present a security risk 225 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 226 | #*.snk 227 | 228 | # Since there are multiple workflows, uncomment next line to ignore bower_components 229 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 230 | #bower_components/ 231 | 232 | # RIA/Silverlight projects 233 | Generated_Code/ 234 | 235 | # Backup & report files from converting an old project file 236 | # to a newer Visual Studio version. Backup files are not needed, 237 | # because we have git ;-) 238 | _UpgradeReport_Files/ 239 | Backup*/ 240 | UpgradeLog*.XML 241 | UpgradeLog*.htm 242 | ServiceFabricBackup/ 243 | *.rptproj.bak 244 | 245 | # SQL Server files 246 | *.mdf 247 | *.ldf 248 | *.ndf 249 | 250 | # Business Intelligence projects 251 | *.rdl.data 252 | *.bim.layout 253 | *.bim_*.settings 254 | *.rptproj.rsuser 255 | 256 | # Microsoft Fakes 257 | FakesAssemblies/ 258 | 259 | # GhostDoc plugin setting file 260 | *.GhostDoc.xml 261 | 262 | # Node.js Tools for Visual Studio 263 | .ntvs_analysis.dat 264 | node_modules/ 265 | 266 | # Visual Studio 6 build log 267 | *.plg 268 | 269 | # Visual Studio 6 workspace options file 270 | *.opt 271 | 272 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 273 | *.vbw 274 | 275 | # Visual Studio LightSwitch build output 276 | **/*.HTMLClient/GeneratedArtifacts 277 | **/*.DesktopClient/GeneratedArtifacts 278 | **/*.DesktopClient/ModelManifest.xml 279 | **/*.Server/GeneratedArtifacts 280 | **/*.Server/ModelManifest.xml 281 | _Pvt_Extensions 282 | 283 | # Paket dependency manager 284 | .paket/paket.exe 285 | paket-files/ 286 | 287 | # FAKE - F# Make 288 | .fake/ 289 | 290 | # JetBrains Rider 291 | .idea/ 292 | *.sln.iml 293 | 294 | # CodeRush 295 | .cr/ 296 | 297 | # Python Tools for Visual Studio (PTVS) 298 | __pycache__/ 299 | *.pyc 300 | 301 | # Cake - Uncomment if you are using it 302 | # tools/** 303 | # !tools/packages.config 304 | 305 | # Tabs Studio 306 | *.tss 307 | 308 | # Telerik's JustMock configuration file 309 | *.jmconfig 310 | 311 | # BizTalk build output 312 | *.btp.cs 313 | *.btm.cs 314 | *.odx.cs 315 | *.xsd.cs 316 | 317 | # OpenCover UI analysis results 318 | OpenCover/ 319 | 320 | # Azure Stream Analytics local run output 321 | ASALocalRun/ 322 | 323 | # MSBuild Binary and Structured Log 324 | *.binlog 325 | 326 | # NVidia Nsight GPU debugger configuration file 327 | *.nvuser 328 | 329 | # MFractors (Xamarin productivity tool) working folder 330 | .mfractor/ 331 | 332 | encrypted-chat-config.json 333 | -------------------------------------------------------------------------------- /EncryptedChat/EncryptedChat.Client.Common/Crypto/RsaCryptographyManager.cs: -------------------------------------------------------------------------------- 1 | namespace EncryptedChat.Client.Common.Crypto 2 | { 3 | using System; 4 | using System.Security.Cryptography; 5 | using System.Text; 6 | using System.Xml; 7 | 8 | public class RsaCryptographyManager 9 | { 10 | private RSA rsa; 11 | 12 | public string EncryptData(byte[] data) 13 | { 14 | if (data == null) 15 | { 16 | throw new ArgumentNullException(nameof(data)); 17 | } 18 | 19 | if (this.rsa == null) 20 | { 21 | throw new InvalidOperationException(); 22 | } 23 | 24 | return Convert.ToBase64String( 25 | this.rsa.Encrypt(data, RSAEncryptionPadding.OaepSHA256) 26 | ); 27 | } 28 | 29 | public byte[] DecryptDataAsByteArray(string data) 30 | { 31 | if (string.IsNullOrWhiteSpace(data)) 32 | { 33 | throw new ArgumentNullException(nameof(data)); 34 | } 35 | 36 | if (this.rsa == null) 37 | { 38 | throw new InvalidOperationException(); 39 | } 40 | 41 | return this.rsa.Decrypt(Convert.FromBase64String(data), 42 | RSAEncryptionPadding.OaepSHA256); 43 | } 44 | 45 | public string SignData(string data) 46 | { 47 | if (this.rsa == null) 48 | { 49 | throw new InvalidOperationException(); 50 | } 51 | 52 | var signature = this.rsa.SignData(Encoding.UTF8.GetBytes(data), 53 | HashAlgorithmName.SHA256, RSASignaturePadding.Pss); 54 | 55 | return Convert.ToBase64String(signature); 56 | } 57 | 58 | public bool VerifySignature(string data, string signature) 59 | { 60 | if (this.rsa == null) 61 | { 62 | throw new InvalidOperationException(); 63 | } 64 | 65 | var isValid = this.rsa.VerifyData(Encoding.UTF8.GetBytes(data), 66 | Convert.FromBase64String(signature), 67 | HashAlgorithmName.SHA256, RSASignaturePadding.Pss); 68 | 69 | return isValid; 70 | } 71 | 72 | public void GenerateNewKey(int keySize = 4096) 73 | { 74 | this.rsa = RSA.Create(keySize); 75 | } 76 | 77 | public string ExportKeyAsXml(bool includePrivateParams = false) 78 | { 79 | if (this.rsa == null) 80 | { 81 | throw new InvalidOperationException(); 82 | } 83 | 84 | return ExportRsaParams(this.rsa, includePrivateParams); 85 | } 86 | 87 | public void LoadKeyFromXml(string xmlString) 88 | { 89 | if (string.IsNullOrWhiteSpace(xmlString)) 90 | { 91 | throw new ArgumentNullException(nameof(xmlString)); 92 | } 93 | 94 | var rsaParameters = CreateRsaParamsFromXmlString(xmlString); 95 | 96 | this.rsa = RSA.Create(rsaParameters); 97 | } 98 | 99 | private static string ExportRsaParams(RSA rsa, bool includePrivateParameters) 100 | { 101 | var rsaParams = rsa.ExportParameters(includePrivateParameters); 102 | var sb = new StringBuilder(); 103 | 104 | sb.Append(""); 105 | sb.Append("" + Convert.ToBase64String(rsaParams.Modulus) + ""); 106 | sb.Append("" + Convert.ToBase64String(rsaParams.Exponent) + ""); 107 | 108 | if (includePrivateParameters) 109 | { 110 | sb.Append("

" + Convert.ToBase64String(rsaParams.P) + "

"); 111 | sb.Append("" + Convert.ToBase64String(rsaParams.Q) + ""); 112 | sb.Append("" + Convert.ToBase64String(rsaParams.DP) + ""); 113 | sb.Append("" + Convert.ToBase64String(rsaParams.DQ) + ""); 114 | sb.Append("" + Convert.ToBase64String(rsaParams.InverseQ) + ""); 115 | sb.Append("" + Convert.ToBase64String(rsaParams.D) + ""); 116 | } 117 | 118 | sb.Append("
"); 119 | 120 | return sb.ToString(); 121 | } 122 | 123 | private static RSAParameters CreateRsaParamsFromXmlString(string xmlString) 124 | { 125 | var parameters = new RSAParameters(); 126 | 127 | var xmlDoc = new XmlDocument(); 128 | xmlDoc.LoadXml(xmlString); 129 | 130 | if (xmlDoc.DocumentElement.Name.Equals("RSAKeyValue")) 131 | { 132 | foreach (XmlNode node in xmlDoc.DocumentElement.ChildNodes) 133 | { 134 | switch (node.Name) 135 | { 136 | case "Modulus": 137 | parameters.Modulus = Convert.FromBase64String(node.InnerText); 138 | 139 | break; 140 | case "Exponent": 141 | parameters.Exponent = Convert.FromBase64String(node.InnerText); 142 | 143 | break; 144 | case "P": 145 | parameters.P = Convert.FromBase64String(node.InnerText); 146 | 147 | break; 148 | case "Q": 149 | parameters.Q = Convert.FromBase64String(node.InnerText); 150 | 151 | break; 152 | case "DP": 153 | parameters.DP = Convert.FromBase64String(node.InnerText); 154 | 155 | break; 156 | case "DQ": 157 | parameters.DQ = Convert.FromBase64String(node.InnerText); 158 | 159 | break; 160 | case "InverseQ": 161 | parameters.InverseQ = Convert.FromBase64String(node.InnerText); 162 | 163 | break; 164 | case "D": 165 | parameters.D = Convert.FromBase64String(node.InnerText); 166 | 167 | break; 168 | } 169 | } 170 | } 171 | else 172 | { 173 | throw new ArgumentException("Invalid XML RSA key."); 174 | } 175 | 176 | return parameters; 177 | } 178 | 179 | public string GetSha256Fingerprint() 180 | { 181 | if (this.rsa == null) 182 | { 183 | throw new InvalidOperationException(); 184 | } 185 | 186 | var rsaParams = this.rsa.ExportParameters(false); 187 | 188 | byte[] hashBytes; 189 | using (SHA256 sha256 = new SHA256Managed()) 190 | { 191 | hashBytes = sha256.ComputeHash(rsaParams.Modulus); 192 | } 193 | 194 | var sb = new StringBuilder(95); 195 | for (var i = 0; i < hashBytes.Length; i++) 196 | { 197 | byte b = hashBytes[i]; 198 | sb.Append(b.ToString("X2")); 199 | 200 | if (i < hashBytes.Length - 1) 201 | { 202 | sb.Append(':'); 203 | } 204 | } 205 | 206 | return sb.ToString(); 207 | } 208 | } 209 | } -------------------------------------------------------------------------------- /EncryptedChat/EncryptedChat.Client.App/Engine.cs: -------------------------------------------------------------------------------- 1 | namespace EncryptedChat.Client.App 2 | { 3 | using System; 4 | using System.Linq; 5 | using System.Text.RegularExpressions; 6 | using System.Threading.Tasks; 7 | using Common; 8 | using Common.Configuration; 9 | using Common.Crypto; 10 | using Microsoft.AspNetCore.SignalR.Client; 11 | using Common.Models; 12 | 13 | public class Engine 14 | { 15 | private HubConnection connection; 16 | private EncryptedCommunicationsManager communicationsManager; 17 | private ConfigurationManager configurationManager; 18 | 19 | private User[] waitingUsers; 20 | private string username; 21 | private State state; 22 | private User otherUser; 23 | 24 | private async Task SetUpConnection() 25 | { 26 | Console.WriteLine(Messages.ConnectingToServer, this.configurationManager.Configuration.ServerUrl); 27 | 28 | this.connection = new HubConnectionBuilder() 29 | .WithUrl(this.configurationManager.Configuration.ServerUrl) 30 | .Build(); 31 | 32 | this.connection.On(nameof(this.UpdateWaitingList), this.UpdateWaitingList); 33 | this.connection.On(nameof(this.AcceptConnection), this.AcceptConnection); 34 | this.connection.On(nameof(this.NewMessage), this.NewMessage); 35 | this.connection.On(nameof(this.Disconnect), this.Disconnect); 36 | 37 | await this.connection.StartAsync(); 38 | 39 | Console.WriteLine(Messages.Connected); 40 | } 41 | 42 | private void LoadUsername() 43 | { 44 | this.username = this.configurationManager.Configuration.Username; 45 | 46 | Regex usernameRegex = new Regex(Constants.UsernameRegex); 47 | 48 | if (!string.IsNullOrWhiteSpace(this.username) && usernameRegex.IsMatch(this.username)) 49 | { 50 | return; 51 | } 52 | 53 | Console.WriteLine(); 54 | Console.WriteLine(Messages.UsernameInfo); 55 | Console.WriteLine(); 56 | 57 | do 58 | { 59 | Console.Write(Messages.UsernamePrompt); 60 | this.username = Console.ReadLine(); 61 | } while (string.IsNullOrWhiteSpace(this.username) || !usernameRegex.IsMatch(this.username)); 62 | 63 | this.configurationManager.Configuration.Username = this.username; 64 | this.configurationManager.SaveChanges(); 65 | } 66 | 67 | private void LoadConfiguration() 68 | { 69 | Console.WriteLine(Messages.LoadingConfiguration); 70 | 71 | this.configurationManager = new ConfigurationManager(Constants.ConfigurationFilePath); 72 | 73 | this.LoadUsername(); 74 | 75 | this.communicationsManager = new EncryptedCommunicationsManager(); 76 | 77 | this.LoadPrivateKey(); 78 | } 79 | 80 | public async Task Setup() 81 | { 82 | this.LoadConfiguration(); 83 | 84 | await this.SetUpConnection(); 85 | 86 | this.state = State.SelectingUser; 87 | 88 | await this.StartReadingInput(); 89 | } 90 | 91 | private async Task StartReadingInput() 92 | { 93 | while (true) 94 | { 95 | string input = Console.ReadLine(); 96 | 97 | if (input == Commands.ExitCommand || 98 | this.connection.State == HubConnectionState.Disconnected || 99 | this.state == State.Disconnected) 100 | { 101 | Console.WriteLine(Messages.Disconnected); 102 | 103 | if (this.connection.State != HubConnectionState.Disconnected) 104 | { 105 | await this.connection.StopAsync(); 106 | } 107 | 108 | break; 109 | } 110 | 111 | switch (this.state) 112 | { 113 | case State.SelectingUser: 114 | await this.UserSelect(input); 115 | break; 116 | case State.InChat: 117 | if (input == Commands.TrustCommand) 118 | { 119 | this.TrustCurrentUser(); 120 | break; 121 | } 122 | 123 | await this.SendMessage(input); 124 | break; 125 | } 126 | } 127 | } 128 | 129 | private async Task SendMessage(string message) 130 | { 131 | if (string.IsNullOrWhiteSpace(message)) 132 | { 133 | return; 134 | } 135 | 136 | message = message.Trim(); 137 | 138 | var encryptedMessage = this.communicationsManager.EncryptMessage(message); 139 | 140 | await this.connection.InvokeCoreAsync("SendMessage", new object[] 141 | { 142 | encryptedMessage 143 | }); 144 | } 145 | 146 | private async Task UserSelect(string input) 147 | { 148 | if (this.waitingUsers == null) 149 | { 150 | return; 151 | } 152 | 153 | if (!int.TryParse(input, out int selected) || 154 | selected < 0 || 155 | selected > this.waitingUsers.Length) 156 | { 157 | Console.WriteLine(Messages.InvalidUserIdSelectedError, this.waitingUsers.Length); 158 | return; 159 | } 160 | 161 | if (selected == 0) 162 | { 163 | await this.JoinAsWaitingUser(); 164 | return; 165 | } 166 | 167 | var selectedUser = this.waitingUsers[selected - 1]; 168 | 169 | await this.ConnectWithUser(selectedUser); 170 | } 171 | 172 | private async Task ConnectWithUser(User selectedUser) 173 | { 174 | Console.Clear(); 175 | Console.WriteLine(Messages.GeneratingSessionKey); 176 | 177 | this.communicationsManager.ImportOtherRsaKey(selectedUser.PublicKey); 178 | string aesKey = this.communicationsManager.GenerateEncryptedAesKey(); 179 | string key = this.communicationsManager.ExportOwnRsaKey(); 180 | string signature = this.communicationsManager.SignData(aesKey); 181 | 182 | Console.WriteLine(Messages.InitialisingEncryptedConnection); 183 | 184 | await this.connection.InvokeCoreAsync("ConnectToUser", new object[] 185 | { 186 | this.username, selectedUser.Id, aesKey, key, signature 187 | }); 188 | 189 | this.CreateChatWithUser(selectedUser); 190 | } 191 | 192 | private void CreateChatWithUser(User user) 193 | { 194 | this.state = State.InChat; 195 | 196 | Regex usernameRegex = new Regex(Constants.UsernameRegex); 197 | 198 | if (string.IsNullOrWhiteSpace(user.Username) || !usernameRegex.IsMatch(user.Username)) 199 | { 200 | Console.WriteLine(Messages.OtherUsernameInvalid); 201 | this.Disconnect(); 202 | return; 203 | } 204 | 205 | this.otherUser = user; 206 | 207 | bool isTrusted = this.IsUserTrusted(this.otherUser); 208 | 209 | string trustedBadge = isTrusted 210 | ? Messages.UserTrustedBadge 211 | : Messages.UserNotTrustedBadge; 212 | 213 | Console.WriteLine(); 214 | Console.WriteLine(Messages.ConnectedWithUser, user.Username, trustedBadge); 215 | Console.WriteLine(); 216 | Console.WriteLine(Messages.CurrentUserFingerprint, this.communicationsManager.GetOwnRsaFingerprint()); 217 | Console.WriteLine(); 218 | 219 | if (!isTrusted) 220 | { 221 | Console.WriteLine(Messages.OtherUserFingerprint, this.otherUser.Username, 222 | this.communicationsManager.GetOtherRsaFingerprint()); 223 | Console.WriteLine(); 224 | 225 | Console.WriteLine(new string('-', 30)); 226 | Console.WriteLine(); 227 | Console.WriteLine(Messages.UserNotTrustedMessage); 228 | Console.WriteLine(); 229 | Console.WriteLine(new string('-', 30)); 230 | Console.WriteLine(); 231 | } 232 | } 233 | 234 | private bool IsUserTrusted(User user) 235 | { 236 | if (!this.configurationManager.Configuration.TrustedUsers.ContainsKey(user.Username)) 237 | { 238 | return false; 239 | } 240 | 241 | string keyHash = HashingUtil.GetSha256Hash(user.PublicKey); 242 | 243 | return this.configurationManager.Configuration.TrustedUsers[user.Username] == keyHash; 244 | } 245 | 246 | private void TrustCurrentUser() 247 | { 248 | bool result = this.TrustUser(this.otherUser); 249 | 250 | Console.WriteLine(result ? Messages.UserTrusted : Messages.CouldNotTrustUser); 251 | } 252 | 253 | private bool TrustUser(User user) 254 | { 255 | if (user == null) 256 | { 257 | return false; 258 | } 259 | 260 | if (this.configurationManager.Configuration.TrustedUsers.ContainsKey(user.Username)) 261 | { 262 | return false; 263 | } 264 | 265 | string keyHash = HashingUtil.GetSha256Hash(user.PublicKey); 266 | 267 | this.configurationManager.Configuration.TrustedUsers.Add(user.Username, keyHash); 268 | 269 | this.configurationManager.SaveChanges(); 270 | 271 | return true; 272 | } 273 | 274 | private void UpdateWaitingList(User[] users) 275 | { 276 | if (this.state != State.SelectingUser) 277 | { 278 | return; 279 | } 280 | 281 | Regex usernameRegex = new Regex(Constants.UsernameRegex); 282 | 283 | this.waitingUsers = users.Where(user => 284 | !string.IsNullOrWhiteSpace(user.Username) && 285 | usernameRegex.IsMatch(user.Username)) 286 | .ToArray(); 287 | 288 | int invalidUsernamesDifference = users.Length - this.waitingUsers.Length; 289 | 290 | Console.WriteLine(); 291 | Console.WriteLine(Messages.UserListHeader); 292 | 293 | if (this.waitingUsers.Length == 0) 294 | { 295 | Console.WriteLine(Messages.UserListNoUsers); 296 | } 297 | else 298 | { 299 | for (int i = 0; i < this.waitingUsers.Length; i++) 300 | { 301 | string trustedBadge = this.IsUserTrusted(this.waitingUsers[i]) 302 | ? Messages.UserTrustedBadge 303 | : Messages.UserNotTrustedBadge; 304 | 305 | Console.WriteLine(Messages.UserListItem, i + 1, this.waitingUsers[i].Username, trustedBadge); 306 | } 307 | } 308 | 309 | if (invalidUsernamesDifference != 0) 310 | { 311 | Console.WriteLine(Messages.UserListInvalidUsername, invalidUsernamesDifference, 312 | invalidUsernamesDifference != 1 ? "s" : ""); 313 | } 314 | 315 | Console.WriteLine(Messages.UserListJoin); 316 | } 317 | 318 | private async Task JoinAsWaitingUser() 319 | { 320 | string pubKey = this.communicationsManager.ExportOwnRsaKey(); 321 | 322 | Console.WriteLine(Messages.SendingKeyToServer); 323 | 324 | this.state = State.Waiting; 325 | 326 | await this.connection.InvokeCoreAsync("RegisterAsWaiting", new object[] 327 | { 328 | this.username, pubKey 329 | }); 330 | 331 | Console.Clear(); 332 | 333 | Console.WriteLine(Messages.WaitingForUser); 334 | } 335 | 336 | private void LoadPrivateKey() 337 | { 338 | if (this.configurationManager.Configuration.PrivateKey == null) 339 | { 340 | Console.WriteLine(Messages.GeneratingKeyPair); 341 | 342 | this.communicationsManager.GenerateNewRsaKey(); 343 | 344 | this.configurationManager.Configuration.PrivateKey = 345 | this.communicationsManager.ExportOwnRsaKey(true); 346 | 347 | this.configurationManager.SaveChanges(); 348 | } 349 | else 350 | { 351 | Console.WriteLine(Messages.LoadingPrivateKey); 352 | 353 | this.communicationsManager.ImportOwnRsaKey(this.configurationManager.Configuration.PrivateKey); 354 | } 355 | } 356 | 357 | private void AcceptConnection(string aesKey, string otherUsername, string rsaKey, string signature) 358 | { 359 | if (this.state != State.Waiting) 360 | { 361 | return; 362 | } 363 | 364 | Console.WriteLine(Messages.InitialisingEncryptedConnection); 365 | 366 | this.communicationsManager.ImportOtherRsaKey(rsaKey); 367 | var signatureValid = this.communicationsManager.VerifySignature(aesKey, signature); 368 | if (!signatureValid) 369 | { 370 | Console.WriteLine(Messages.IncomingConnectionSignatureInvalid); 371 | this.Disconnect(); 372 | return; 373 | } 374 | 375 | this.communicationsManager.ImportEncryptedAesKey(aesKey); 376 | 377 | var user = new User 378 | { 379 | Username = otherUsername, 380 | PublicKey = rsaKey 381 | }; 382 | 383 | this.CreateChatWithUser(user); 384 | } 385 | 386 | private void NewMessage(string encryptedMessage, string messageUsername) 387 | { 388 | if (this.state != State.InChat) 389 | { 390 | return; 391 | } 392 | 393 | string decryptedMessage = this.communicationsManager.DecryptMessage(encryptedMessage); 394 | 395 | Console.WriteLine(Messages.MessageFormat, messageUsername, decryptedMessage); 396 | } 397 | 398 | private void Disconnect() 399 | { 400 | Console.WriteLine(Messages.Disconnected); 401 | 402 | this.state = State.Disconnected; 403 | } 404 | } 405 | } --------------------------------------------------------------------------------