From 30eceaed8c0f4b95abfcb8e440b002c08b1d3977 Mon Sep 17 00:00:00 2001 From: ren Date: Tue, 14 May 2024 22:07:39 +0300 Subject: [PATCH] =?UTF-8?q?=D0=A0=D0=B0=D0=B1=D0=BE=D1=82=D0=B0=20=D1=81?= =?UTF-8?q?=20=D1=81=D0=B5=D1=80=D0=B2=D0=B5=D1=80=D0=BE=D0=BC.=20=D0=9F?= =?UTF-8?q?=D0=BE=D0=BF=D1=8B=D1=82=D0=BA=D0=B0=20=D1=81=20RSA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- LauncherDM/App.config | 12 + LauncherDM/Properties/Resources.Designer.cs | 11 +- LauncherDM/Properties/Resources.en.resx | 3 + LauncherDM/Properties/Resources.resx | 3 + LauncherDM/Properties/SettingsApp.Designer.cs | 36 ++ LauncherDM/Properties/SettingsApp.settings | 19 +- LauncherDM/Services/AuthorizationService.cs | 28 ++ LauncherDM/Services/DialogWindowService.cs | 2 +- .../Interfaces/IAuthorizationService.cs | 7 + .../Interfaces/IRegAndLogWindowService.cs | 6 + .../Interfaces/IServerRequestService.cs | 10 +- .../Interfaces/IWindowAnimationsService.cs | 12 + LauncherDM/Services/LoadingWindowService.cs | 3 +- .../Services/RegAndLogWindowServiceService.cs | 8 + LauncherDM/Services/ServerRequestService.cs | 41 +- .../Services/WindowAnimationsService.cs | 13 + LauncherDM/Styles/Other/ButtonStyle.xaml | 46 +- .../ViewModels/AccountUserControlViewModel.cs | 47 +- .../AuthorizationWIndowViewModel.cs | 10 +- .../ViewModels/RegAndLogWindowViewModel.cs | 100 +++- .../UserControls/AccountUserControl.xaml | 8 +- LauncherDM/Views/Windows/AboutProgram.xaml | 14 + LauncherDM/Views/Windows/AboutProgram.xaml.cs | 28 ++ .../Views/Windows/AuthorizationWIndow.xaml | 97 +--- LauncherDM/Views/Windows/RegAndLogWindow.xaml | 466 ++++++++++++++---- ServerTCP/App.config | 18 + ServerTCP/MessageHeader.cs | 77 ++- ServerTCP/Program.cs | 30 +- .../\320\241ryptographies/CryptoRsa.cs" | 50 +- 29 files changed, 900 insertions(+), 305 deletions(-) create mode 100644 LauncherDM/Services/AuthorizationService.cs create mode 100644 LauncherDM/Services/Interfaces/IAuthorizationService.cs create mode 100644 LauncherDM/Services/Interfaces/IRegAndLogWindowService.cs create mode 100644 LauncherDM/Services/Interfaces/IWindowAnimationsService.cs create mode 100644 LauncherDM/Services/RegAndLogWindowServiceService.cs create mode 100644 LauncherDM/Services/WindowAnimationsService.cs create mode 100644 LauncherDM/Views/Windows/AboutProgram.xaml create mode 100644 LauncherDM/Views/Windows/AboutProgram.xaml.cs create mode 100644 ServerTCP/App.config diff --git a/LauncherDM/App.config b/LauncherDM/App.config index 1087598..f18f7b7 100644 --- a/LauncherDM/App.config +++ b/LauncherDM/App.config @@ -2,10 +2,22 @@ +
+ + + 127.0.0.1 + + + 25590 + + + + + diff --git a/LauncherDM/Properties/Resources.Designer.cs b/LauncherDM/Properties/Resources.Designer.cs index 74b98ea..19bd6f6 100644 --- a/LauncherDM/Properties/Resources.Designer.cs +++ b/LauncherDM/Properties/Resources.Designer.cs @@ -96,6 +96,15 @@ internal static string ConnectClose { } } + /// + /// Ищет локализованную строку, похожую на . + /// + internal static string Email { + get { + return ResourceManager.GetString("Email", resourceCulture); + } + } + /// /// Ищет локализованную строку, похожую на Ошибка!. /// @@ -115,7 +124,7 @@ internal static string EthernetClose { } /// - /// Ищет локализованную строку, похожую на . + /// Ищет локализованную строку, похожую на Забыли пароль. /// internal static string ForgotPassword { get { diff --git a/LauncherDM/Properties/Resources.en.resx b/LauncherDM/Properties/Resources.en.resx index cca92cc..eb7abe5 100644 --- a/LauncherDM/Properties/Resources.en.resx +++ b/LauncherDM/Properties/Resources.en.resx @@ -56,4 +56,7 @@ Forgot password + + Email + \ No newline at end of file diff --git a/LauncherDM/Properties/Resources.resx b/LauncherDM/Properties/Resources.resx index 1a0b468..6333e20 100644 --- a/LauncherDM/Properties/Resources.resx +++ b/LauncherDM/Properties/Resources.resx @@ -143,4 +143,7 @@ Забыли пароль + + Почта + \ No newline at end of file diff --git a/LauncherDM/Properties/SettingsApp.Designer.cs b/LauncherDM/Properties/SettingsApp.Designer.cs index 96b8dc8..ff23bca 100644 --- a/LauncherDM/Properties/SettingsApp.Designer.cs +++ b/LauncherDM/Properties/SettingsApp.Designer.cs @@ -22,5 +22,41 @@ public static SettingsApp Default { return defaultInstance; } } + + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("127.0.0.1")] + public string Ip { + get { + return ((string)(this["Ip"])); + } + set { + this["Ip"] = value; + } + } + + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("25590")] + public string Port { + get { + return ((string)(this["Port"])); + } + set { + this["Port"] = value; + } + } + + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("")] + public string Token { + get { + return ((string)(this["Token"])); + } + set { + this["Token"] = value; + } + } } } diff --git a/LauncherDM/Properties/SettingsApp.settings b/LauncherDM/Properties/SettingsApp.settings index 049245f..c07553c 100644 --- a/LauncherDM/Properties/SettingsApp.settings +++ b/LauncherDM/Properties/SettingsApp.settings @@ -1,6 +1,15 @@  - - - - - + + + + + 127.0.0.1 + + + 25590 + + + + + + \ No newline at end of file diff --git a/LauncherDM/Services/AuthorizationService.cs b/LauncherDM/Services/AuthorizationService.cs new file mode 100644 index 0000000..82489ee --- /dev/null +++ b/LauncherDM/Services/AuthorizationService.cs @@ -0,0 +1,28 @@ +using LauncherDM.Services.Interfaces; +using ServerTCP; +using ServerTCP.Сryptographies; + +namespace LauncherDM.Services +{ + internal class AuthorizationService : IAuthorizationService + { + private IServerRequestService _serverRequest; + public bool Authorization(string login, string password) + { + //var requestPublicKey = _serverRequest.SendMessageRequest(MessageHeader.MessageType.PublicKey); + //var publicKey = requestPublicKey.Message.ToString(); + + var data = string.Concat(login, ",", password); + //var cryptMessage = CryptoRsa.Encrypt(publicKey, data); + //var requestToken = _serverRequest.SendMessageRequest(cryptMessage, MessageHeader.MessageType.Login); + + var requestToken = _serverRequest.SendMessageRequest(data, MessageHeader.MessageType.Login); + return false; + } + + public AuthorizationService() + { + _serverRequest = new ServerRequestService(); + } + } +} diff --git a/LauncherDM/Services/DialogWindowService.cs b/LauncherDM/Services/DialogWindowService.cs index 6544243..758dee8 100644 --- a/LauncherDM/Services/DialogWindowService.cs +++ b/LauncherDM/Services/DialogWindowService.cs @@ -27,7 +27,7 @@ public void OpenWindow(object viewModel) authorization.Show(); return; } - else if (viewModel is AuthorizationWindowViewModel) + else if (viewModel is AccountUserControlViewModel or AuthorizationWindowViewModel) { var regAndLogWindow = new RegAndLogWindow(); regAndLogWindow.DataContext = new RegAndLogWindowViewModel(new ToolbarToWindowViewModel(new WindowService(regAndLogWindow)), diff --git a/LauncherDM/Services/Interfaces/IAuthorizationService.cs b/LauncherDM/Services/Interfaces/IAuthorizationService.cs new file mode 100644 index 0000000..42596b5 --- /dev/null +++ b/LauncherDM/Services/Interfaces/IAuthorizationService.cs @@ -0,0 +1,7 @@ +namespace LauncherDM.Services.Interfaces +{ + internal interface IAuthorizationService + { + bool Authorization(string login, string password); + } +} diff --git a/LauncherDM/Services/Interfaces/IRegAndLogWindowService.cs b/LauncherDM/Services/Interfaces/IRegAndLogWindowService.cs new file mode 100644 index 0000000..8bebde7 --- /dev/null +++ b/LauncherDM/Services/Interfaces/IRegAndLogWindowService.cs @@ -0,0 +1,6 @@ +namespace LauncherDM.Services.Interfaces +{ + interface IRegAndLogWindowService + { + } +} diff --git a/LauncherDM/Services/Interfaces/IServerRequestService.cs b/LauncherDM/Services/Interfaces/IServerRequestService.cs index e733d5e..12a2ee3 100644 --- a/LauncherDM/Services/Interfaces/IServerRequestService.cs +++ b/LauncherDM/Services/Interfaces/IServerRequestService.cs @@ -1,16 +1,12 @@ using ServerTCP; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using static ServerTCP.MessageLanguages; namespace LauncherDM.Services.Interfaces { interface IServerRequestService { - public MessageHeader SendMessageRequest(string data, MessageHeader.MessageType messageType, int length); + public MessageHeader SendMessageRequest(object data, MessageHeader.MessageType messageType, bool loadToken = false); - public MessageHeader SendMessageRequest(MessageHeader.MessageType messageType); + public MessageHeader SendMessageRequest(MessageHeader.MessageType messageType, bool loadToken = false); } } diff --git a/LauncherDM/Services/Interfaces/IWindowAnimationsService.cs b/LauncherDM/Services/Interfaces/IWindowAnimationsService.cs new file mode 100644 index 0000000..10d8f57 --- /dev/null +++ b/LauncherDM/Services/Interfaces/IWindowAnimationsService.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace LauncherDM.Services.Interfaces +{ + interface IWindowAnimationsService + { + } +} diff --git a/LauncherDM/Services/LoadingWindowService.cs b/LauncherDM/Services/LoadingWindowService.cs index b89f58e..4c2a414 100644 --- a/LauncherDM/Services/LoadingWindowService.cs +++ b/LauncherDM/Services/LoadingWindowService.cs @@ -1,5 +1,4 @@ -using System; -using System.Reflection; +using System.Reflection; using LauncherDM.Services.Interfaces; using ServerTCP; diff --git a/LauncherDM/Services/RegAndLogWindowServiceService.cs b/LauncherDM/Services/RegAndLogWindowServiceService.cs new file mode 100644 index 0000000..586823e --- /dev/null +++ b/LauncherDM/Services/RegAndLogWindowServiceService.cs @@ -0,0 +1,8 @@ +using LauncherDM.Services.Interfaces; + +namespace LauncherDM.Services +{ + class RegAndLogWindowServiceService : IRegAndLogWindowService + { + } +} diff --git a/LauncherDM/Services/ServerRequestService.cs b/LauncherDM/Services/ServerRequestService.cs index 98979a1..dfd609a 100644 --- a/LauncherDM/Services/ServerRequestService.cs +++ b/LauncherDM/Services/ServerRequestService.cs @@ -2,10 +2,10 @@ using System; using System.Linq; using System.Net; -using System.Net.Http; using System.Net.Sockets; -using System.Windows.Markup; using ServerTCP; +using LauncherDM.Properties; +using static ServerTCP.MessageLanguages; namespace LauncherDM.Services { @@ -14,19 +14,16 @@ namespace LauncherDM.Services /// class ServerRequestService : IServerRequestService { - private static readonly string _ip = DataInfo.Ip; - private static readonly int _port = DataInfo.Port; - private IPAddress _ipAddress; private IPEndPoint _endPoint; public ServerRequestService() { - _ipAddress = IPAddress.Parse(_ip); - _endPoint = new IPEndPoint(_ipAddress, _port); + _ipAddress = IPAddress.Parse(SettingsApp.Default.Ip); + _endPoint = new IPEndPoint(_ipAddress, int.Parse(SettingsApp.Default.Port)); } - public MessageHeader SendMessageRequest(string data, MessageHeader.MessageType messageType, int length) + public MessageHeader SendMessageRequest(object data, MessageHeader.MessageType messageType, bool loadToken = false) { TcpClient tcpClient = null; try @@ -36,31 +33,25 @@ public MessageHeader SendMessageRequest(string data, MessageHeader.MessageType m tcpClient = new TcpClient(); tcpClient.Connect(_endPoint); - var messageHeader = new MessageHeader(data, messageType); - byte[] headerBytes = messageHeader.MessageToArray(); - + var messageHeader = new MessageHeader(data, messageType, MessageLanguages.Language); + byte[] headerBytes = messageHeader.MessageToArray(loadToken); NetworkStream tcpStream = tcpClient.GetStream(); tcpStream.Write(headerBytes); do { - byte[] getBytes = new byte[tcpClient.ReceiveBufferSize]; - tcpStream.Read(getBytes, 0, tcpClient.ReceiveBufferSize); - var defaultData = getBytes.Skip(1).Take(5); - var size = 0; - foreach (var sizeData in defaultData) - size += sizeData; - getBytes = getBytes.Take(size + MessageHeader.LengthAndDataType).ToArray(); - return MessageHeader.FromArray(getBytes); + var getBytes = new byte[tcpClient.ReceiveBufferSize]; + var lengthByte = tcpStream.Read(getBytes, 0, tcpClient.ReceiveBufferSize); + return MessageHeader.FromArray(getBytes.Take(lengthByte).ToArray()); } while (tcpStream.DataAvailable); } } catch (Exception e) { - //IResourcesHelperService resourcesHelper = new ResourcesHelperService(); - IDialogMessageBoxService dialogMessageBox = new DialogMessageBoxService(); - dialogMessageBox.DialogShow("Error Server Reques", "Error Server Reques"); + ////IResourcesHelperService resourcesHelper = new ResourcesHelperService(); + //IDialogMessageBoxService dialogMessageBox = new DialogMessageBoxService(); + //dialogMessageBox.DialogShow("Error Server Reques", "Error Server Reques"); return null; } finally @@ -69,7 +60,7 @@ public MessageHeader SendMessageRequest(string data, MessageHeader.MessageType m } } - public MessageHeader SendMessageRequest(MessageHeader.MessageType messageType) + public MessageHeader SendMessageRequest(MessageHeader.MessageType messageType, bool loadToken = false) { TcpClient tcpClient = null; try @@ -79,8 +70,8 @@ public MessageHeader SendMessageRequest(MessageHeader.MessageType messageType) tcpClient = new TcpClient(); tcpClient.Connect(_endPoint); - var messageHeader = new MessageHeader(messageType); - byte[] headerBytes = messageHeader.MessageToArray(); + var messageHeader = new MessageHeader(messageType, MessageLanguages.Language); + byte[] headerBytes = messageHeader.MessageToArray(loadToken); NetworkStream tcpStream = tcpClient.GetStream(); tcpStream.Write(headerBytes); diff --git a/LauncherDM/Services/WindowAnimationsService.cs b/LauncherDM/Services/WindowAnimationsService.cs new file mode 100644 index 0000000..580ae4a --- /dev/null +++ b/LauncherDM/Services/WindowAnimationsService.cs @@ -0,0 +1,13 @@ +using LauncherDM.Services.Interfaces; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace LauncherDM.Services +{ + class WindowAnimationsService : IWindowAnimationsService + { + } +} diff --git a/LauncherDM/Styles/Other/ButtonStyle.xaml b/LauncherDM/Styles/Other/ButtonStyle.xaml index ece02c8..280c02c 100644 --- a/LauncherDM/Styles/Other/ButtonStyle.xaml +++ b/LauncherDM/Styles/Other/ButtonStyle.xaml @@ -204,7 +204,7 @@ - + @@ -329,4 +329,48 @@ + + \ No newline at end of file diff --git a/LauncherDM/ViewModels/AccountUserControlViewModel.cs b/LauncherDM/ViewModels/AccountUserControlViewModel.cs index f66ff80..b08ecf1 100644 --- a/LauncherDM/ViewModels/AccountUserControlViewModel.cs +++ b/LauncherDM/ViewModels/AccountUserControlViewModel.cs @@ -1,16 +1,40 @@ - -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Windows.Controls; +using System; +using LauncherDM.Infastructure.Commands; +using LauncherDM.Infastructure.Commands.Base; +using LauncherDM.Services; +using LauncherDM.Services.Interfaces; namespace LauncherDM.ViewModels { public class AccountUserControlViewModel : ViewModel.Base.ViewModel { + #region Fields + + private Action _closeAction; + + #endregion + + #region Services + + private readonly IDialogWindowService _windowService; + + #endregion + + #region Commands + + public Command ShowRegAndLogFormCommand { get; } + + private bool CanShowRegAndLogFormCommandExecute(object p) => true; + + private void OnShowRegAndLogFormCommandExecuted(object p) + { + _windowService.OpenWindow(this); + _windowService.CloseAction = _closeAction; + _windowService.CloseWindow(); + } + + #endregion + #region Bindings #region NameAccount @@ -37,14 +61,15 @@ public string DisplayedImagePath #endregion - - #endregion - public AccountUserControlViewModel(string accountName, string imagePath) + public AccountUserControlViewModel(Action closeMainWindow, string accountName, string imagePath) { AccountName = accountName; DisplayedImagePath = imagePath; + _closeAction = closeMainWindow; + _windowService = new DialogWindowService(); + ShowRegAndLogFormCommand = new lambdaCommand(OnShowRegAndLogFormCommandExecuted, CanShowRegAndLogFormCommandExecute); } } } diff --git a/LauncherDM/ViewModels/AuthorizationWIndowViewModel.cs b/LauncherDM/ViewModels/AuthorizationWIndowViewModel.cs index e72ee19..bdbc27d 100644 --- a/LauncherDM/ViewModels/AuthorizationWIndowViewModel.cs +++ b/LauncherDM/ViewModels/AuthorizationWIndowViewModel.cs @@ -97,11 +97,11 @@ public AuthorizationWindowViewModel(Action dragMove, Action closeWindowAction ,T _accountList = new ObservableCollection() { - new AccountUserControlViewModel("Sex", "/Source/Images/Logo/MilkBottle.png"), - new AccountUserControlViewModel("Sex", ""), - new AccountUserControlViewModel("Sex", ""), - new AccountUserControlViewModel("Sex", ""), - new AccountUserControlViewModel("Sex", ""), + new AccountUserControlViewModel(closeWindowAction,"Sex", "/Source/Images/Logo/MilkBottle.png"), + new AccountUserControlViewModel(closeWindowAction,"Sex", ""), + new AccountUserControlViewModel(closeWindowAction,"Sex", ""), + new AccountUserControlViewModel(closeWindowAction,"Sex", ""), + new AccountUserControlViewModel(closeWindowAction,"Sex", ""), }; _windowService = new DialogWindowService(); diff --git a/LauncherDM/ViewModels/RegAndLogWindowViewModel.cs b/LauncherDM/ViewModels/RegAndLogWindowViewModel.cs index bb7b375..2b6515c 100644 --- a/LauncherDM/ViewModels/RegAndLogWindowViewModel.cs +++ b/LauncherDM/ViewModels/RegAndLogWindowViewModel.cs @@ -1,15 +1,7 @@ using LauncherDM.Services.Interfaces; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using LauncherDM.Services; using LauncherDM.ViewModels.UserControlsVM; -using System.Windows; using System.Reflection; -using LauncherDM.Views.Windows; -using System.Windows.Input; using LauncherDM.Infastructure.Commands.Base; using LauncherDM.Infastructure.Commands; @@ -21,6 +13,10 @@ class RegAndLogWindowViewModel : ViewModel.Base.ViewModel private readonly IResourcesHelperService _resourcesHelper; + private readonly IDialogWindowService _dialogWindow; + + private readonly IRegAndLogWindowService _regAndLogWindowService; + #endregion #region Bindings @@ -37,6 +33,8 @@ class RegAndLogWindowViewModel : ViewModel.Base.ViewModel public string RememberMeText =>_resourcesHelper.LocalizationGet("RememberMe"); + public string EmailText => _resourcesHelper.LocalizationGet("Email"); + public string ForgotPasswordText => _resourcesHelper.LocalizationGet("ForgotPassword"); public string VersionText => string.Concat("Version: ", Assembly.GetExecutingAssembly().GetName().Version?.ToString() ?? string.Empty); @@ -53,6 +51,54 @@ public ToolbarToWindowViewModel ToolbarVM #endregion + #region Login + + private string _login; + + public string Login + { + get => _login; + set => Set(ref _login, value); + } + + private string _password; + + public string Password + { + get => _password; + set => Set(ref _password, value); + } + + #endregion + + #region SugnUp + + private string _regLogin; + + public string RegLogin + { + get => _regLogin; + set => Set(ref _regLogin, value); + } + + private string _email; + + public string Email + { + get => _email; + set => Set(ref _email, value); + } + + private string _regPassword; + + public string RegPassword + { + get => _regPassword; + set => Set(ref _regPassword, value); + } + + #endregion + #endregion #region Commmands @@ -63,8 +109,38 @@ public ToolbarToWindowViewModel ToolbarVM private bool CanShowAccountRecoveryWindowCommandExecute(object p) => true; private void OnShowAccountRecoveryWindowCommandExecuted(object p) { - IDialogWindowService windowService = new DialogWindowService(); - windowService.OpenAccountRecovery(); + _dialogWindow.OpenAccountRecovery(); + } + + #endregion + + #region Login + + public Command LoginCommand { get; } + private bool CanLoginCommandExecute(object p) => true; + private void OnLoginCommandExecuted(object p) + { + IAuthorizationService authorization = new AuthorizationService(); + if (authorization.Authorization(Login, Password)) + { + + } + else + { + IDialogMessageBoxService dialogMessageBox = new DialogMessageBoxService(); + dialogMessageBox.DialogShow("Error Server Reques", "Error Server Reques"); + } + } + + #endregion + + #region SignUp + + public Command SignUpCommand { get; } + private bool CanSignUpCommandExecute(object p) => true; + private void OnSignUpCommandExecuted(object p) + { + } #endregion @@ -75,7 +151,11 @@ public RegAndLogWindowViewModel(ToolbarToWindowViewModel toolbarViewModel, Resou { _resourcesHelper = resourcesHelper; ToolbarVM = toolbarViewModel; + _dialogWindow = new DialogWindowService(); + _regAndLogWindowService = new RegAndLogWindowServiceService(); ShowAccountRecoveryWindowCommand = new lambdaCommand(OnShowAccountRecoveryWindowCommandExecuted, CanShowAccountRecoveryWindowCommandExecute); + LoginCommand = new lambdaCommand(OnLoginCommandExecuted, CanLoginCommandExecute); + SignUpCommand = new lambdaCommand(OnSignUpCommandExecuted, CanSignUpCommandExecute); } } } diff --git a/LauncherDM/Views/UserControls/AccountUserControl.xaml b/LauncherDM/Views/UserControls/AccountUserControl.xaml index afd226c..5b5c518 100644 --- a/LauncherDM/Views/UserControls/AccountUserControl.xaml +++ b/LauncherDM/Views/UserControls/AccountUserControl.xaml @@ -19,12 +19,8 @@ - - + + + + + + + + + + diff --git a/ServerTCP/App.config b/ServerTCP/App.config new file mode 100644 index 0000000..b9cab94 --- /dev/null +++ b/ServerTCP/App.config @@ -0,0 +1,18 @@ + + + + +
+ + + + + + + + + + + + + \ No newline at end of file diff --git a/ServerTCP/MessageHeader.cs b/ServerTCP/MessageHeader.cs index f435bc8..2ade2cc 100644 --- a/ServerTCP/MessageHeader.cs +++ b/ServerTCP/MessageHeader.cs @@ -17,6 +17,7 @@ public enum MessageType : byte { Session, Token, + Login, Registration, Version, Log, @@ -26,6 +27,7 @@ public enum MessageType : byte Check, Title, TitleLoading, + PublicKey, } public MessageType Type { get; } @@ -42,6 +44,12 @@ public MessageHeader(MessageType type, MessageLanguages.Languages lang, string t Token = token; } + public MessageHeader(MessageType type, string token) + { + Type = type; + Token = token; + } + public MessageHeader(object message, MessageType type, MessageLanguages.Languages lang, string token) { Message = message; @@ -50,6 +58,13 @@ public MessageHeader(object message, MessageType type, MessageLanguages.Language Token = token; } + public MessageHeader(object message, MessageType type, MessageLanguages.Languages lang) + { + Message = message; + Type = type; + Language = lang; + } + public MessageHeader(object message, MessageType type) { Message = message; @@ -76,12 +91,13 @@ public byte[] MessageToArray(bool loadToken = false) { var message = new byte[]{}; - //switch (Type) - //{ - // default: - // return result; - // break; - //} + switch (Type) + { + case MessageType.Login: + //message = (byte[])Message; + Encoding.UTF8.GetBytes(Message.ToString()); + break; + } var messageLength = message.Length; int lengthByte = loadToken ? messageLength + TokenLength + LengthAndDataType : messageLength + LengthAndDataType; @@ -90,17 +106,20 @@ public byte[] MessageToArray(bool loadToken = false) result[0] = (byte)Type; result[1] = (byte)Language; result[2] = loadToken ? (byte)1 : (byte)0; // 1 - токен есть | 0 - без токена(размер токена 10 байт) - if (messageLength > 0) - BinaryPrimitives.WriteInt32LittleEndian(result.AsSpan().Slice(3, 5), lengthByte); - - //if (loadToken) - //{ - // Array.Copy(Encoding.UTF8.GetBytes("1234567890"), 0, result, LengthAndDataType, TokenLength); - // Array.Copy(message ?? [0], 0, result, LengthAndDataType + TokenLength, Length); - //} - //else - // Array.Copy(message ?? [0], 0, result, 6, Length); - + var bytes = BitConverter.GetBytes(lengthByte).Where(x => x != 0).ToArray(); + + if (bytes.Length > 3) + throw new ArgumentException(nameof(bytes)); + + + switch (Type) + { + case MessageType.Login: + Array.Copy(bytes, 0, result, 3, bytes.Length); + Array.Copy(message ?? [0], 0, result, LengthAndDataType, messageLength); + break; + } + return result; } @@ -116,16 +135,12 @@ internal byte[] MessageServerToArray(bool loadToken = false) switch (Type) { case MessageType.Token: - message = Encoding.UTF8.GetBytes("1234567890"); - break; case MessageType.TitleLoading: + case MessageType.PublicKey: case MessageType.Version: case MessageType.Check: message = Encoding.UTF8.GetBytes(Message.ToString()); break; - default: - message = Encoding.UTF8.GetBytes("1"); - break; } var messageLength = message.Length; @@ -156,14 +171,26 @@ public static MessageHeader FromArray(ReadOnlySpan buffer) { case MessageHeader.MessageType.TitleLoading: case MessageHeader.MessageType.Version: + case MessageHeader.MessageType.PublicKey: case MessageHeader.MessageType.Check: + case MessageHeader.MessageType.Login: return new MessageHeader(Encoding.UTF8.GetString(buffer.ToArray(), LengthAndDataType, buffer.Length - LengthAndDataType), (MessageType)buffer[0]); break; - case MessageHeader.MessageType.Token: + case MessageHeader.MessageType.Session: //return new MessageHeader(Encoding.UTF8.GetString(buffer.ToArray(), LengthAndDataType, buffer.Length - LengthAndDataType), (MessageType)buffer[0], BinaryPrimitives.ReadInt32LittleEndian(buffer[1..])); // сохраняем, добавляем данные. Данные передаются в кодированном формате, будем использовать кодировку UTF8, раскодируем байты - return new MessageHeader((MessageType)buffer[0], (MessageLanguages.Languages)buffer[1], Encoding.UTF8.GetString(buffer.ToArray(), LengthAndDataType, buffer.Length - LengthAndDataType)); + return new MessageHeader((MessageType)buffer[0], + (MessageLanguages.Languages)buffer[1], + Encoding.UTF8.GetString(buffer.ToArray(), LengthAndDataType, buffer.Length - LengthAndDataType)); break; - case MessageHeader.MessageType.Session: + case MessageHeader.MessageType.Token: + return new MessageHeader((MessageType)buffer[0], + Encoding.UTF8.GetString(buffer.ToArray(), LengthAndDataType, buffer.Length - LengthAndDataType)); + break; + //case MessageHeader.MessageType.Login: + // var result = buffer[LengthAndDataType..buffer.Length]; + // return new MessageHeader(result.ToArray(), + // (MessageType)buffer[0]); + // break; case MessageHeader.MessageType.Registration: case MessageHeader.MessageType.Log: case MessageHeader.MessageType.File: diff --git a/ServerTCP/Program.cs b/ServerTCP/Program.cs index 0eceb30..6f7f58c 100644 --- a/ServerTCP/Program.cs +++ b/ServerTCP/Program.cs @@ -8,6 +8,8 @@ using System.Reflection.Metadata; using System.Runtime.CompilerServices; using System.Security.Cryptography; +using ServerTCP.Properties; +using ServerTCP.Сryptographies; namespace ServerTCP { @@ -16,8 +18,13 @@ internal class Program private static readonly string ip = DataInfo.Ip; private static readonly int port = DataInfo.Port; + private static string _publicKey; + private static string _privateKey; + static void Main(string[] args) { + LoadingRSA(); + var ipAddress = IPAddress.Parse(ip); var endPoint = new IPEndPoint(ipAddress, port); @@ -34,7 +41,7 @@ static void Main(string[] args) Console.WriteLine("Ожидаем соединение через порт {0}", endPoint); var listener = tcpSocket.Accept(); // новый с окет для нового клиента Console.WriteLine("Подключился!"); - var buffer = new byte[256]; // размер буфера . максимум сообщение из 256 байт + var buffer = new byte[listener.ReceiveBufferSize]; // размер буфера . максимум сообщение из 256 байт var size = 0; // количество реально полученных количества байт, потом чтобы оптимизировать память do { @@ -50,10 +57,11 @@ static void Main(string[] args) case MessageHeader.MessageType.Check: headerRequest = new MessageHeader("1", MessageHeader.MessageType.Check); break; - case MessageHeader.MessageType.Token: - message = "1234567890"; - loadToken = true; - headerRequest = new MessageHeader(message, MessageHeader.MessageType.Token); + case MessageHeader.MessageType.Login: + // byte[] s = (byte[])header.Message; + //var r = CryptoRsa.Decrypt(_privateKey, s); + //Console.WriteLine(r); + Console.WriteLine(header.Message.ToString()); break; case MessageHeader.MessageType.Registration: var user = new User @@ -70,6 +78,9 @@ static void Main(string[] args) var version = DataBaseCommands.Select(MessageHeader.MessageType.Version); headerRequest = new MessageHeader(version.ToString(), MessageHeader.MessageType.Version); break; + case MessageHeader.MessageType.PublicKey: + headerRequest = new MessageHeader(_privateKey, MessageHeader.MessageType.PublicKey); + break; } if (headerRequest is not null) @@ -91,5 +102,14 @@ static void Main(string[] args) } } } + + + + private static void LoadingRSA() + { + var (publicKey, privateKey) = CryptoRsa.GenerateKey(); + _publicKey = publicKey; + _privateKey = privateKey; + } } } \ No newline at end of file diff --git "a/ServerTCP/\320\241ryptographies/CryptoRsa.cs" "b/ServerTCP/\320\241ryptographies/CryptoRsa.cs" index 36ae6f4..530a4e8 100644 --- "a/ServerTCP/\320\241ryptographies/CryptoRsa.cs" +++ "b/ServerTCP/\320\241ryptographies/CryptoRsa.cs" @@ -1,24 +1,50 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Security.Cryptography; +using System.Security.Cryptography; using System.Text; -using System.Threading.Tasks; +using static System.Runtime.InteropServices.JavaScript.JSType; namespace ServerTCP.Сryptographies { - internal class CryptoRsa + public class CryptoRsa { - private RSACryptoServiceProvider m_Rsa; - private RSAParameters m_ExternKey; - private RSAParameters m_InternKey; - public CryptoRsa() { - m_Rsa = new RSACryptoServiceProvider(512); - m_InternKey = m_Rsa.ExportParameters(true); + + } + + /// + /// (publicKey, privateKey) + /// + /// + public static (string, string) GenerateKey() + { + using (var rsa = RSA.Create()) + { + var publicKey = rsa.ToXmlString(false); + var privateKey = rsa.ToXmlString(false); + return (publicKey, privateKey); + } + } + public static byte[] Encrypt(string publiKey, string data) + { + using (var rsa = RSA.Create()) + { + rsa.FromXmlString(publiKey); + byte[] messageBytes = Encoding.UTF8.GetBytes(data); + byte[] encryptedBytes = rsa.Encrypt(messageBytes, RSAEncryptionPadding.OaepSHA256); + return encryptedBytes; + } } + public static string Decrypt(string privateKey, byte[] encryptedBytes) + { + using (var rsa = RSA.Create()) + { + rsa.FromXmlString(privateKey); + byte[] decryptedBytes = rsa.Decrypt(encryptedBytes, RSAEncryptionPadding.OaepSHA256); + var decryptedMessage = Encoding.UTF8.GetString(decryptedBytes); + return decryptedMessage; + } + } } } \ No newline at end of file