// загрузить токен private void LoadToken() { // считываем из реестра параметры if ((keyName != null) && (keyName != "")) { // Пробуем считать из реестра токен авторизации для доступа в личный кабинет брокера Тинькофф byte[] bytes = (byte[])Registry.GetValue(keyName, "Token", null); // Дешифруем токен if (bytes != null) { token = CryptoClass.decrypt_function(bytes); } else { token = ""; } if (Ribbon != null) { if (token == "") { Ribbon.grpTinkoff.Label = "Токен НЕ зарегистрирован!"; Ribbon.grpStock.Visible = false; Ribbon.grpInvest.Visible = false; } else { Ribbon.grpTinkoff.Label = "Токен зарегистрирован"; Ribbon.grpStock.Visible = true; Ribbon.grpInvest.Visible = true; } } } }
protected void LoginButton_Click(object sender, EventArgs e) { try { CryptoClass crypto = new CryptoClass(); String id = userIdTb.Text; String password = crypto.Encrypt(PasswordTb.Text); Assignment5ServiceRefs.Service1Client serviceRef = new Assignment5ServiceRefs.Service1Client(); if (serviceRef.checkUserCredentials(id, password)) { HttpCookie userCookies = new HttpCookie("userInfo"); userCookies["id"] = userIdTb.Text; userCookies.Expires = DateTime.Now.AddMonths(6); Response.Cookies.Add(userCookies); FormsAuthentication.RedirectFromLoginPage(userIdTb.Text, Persistent.Checked); Session["type"] = "member"; userCookies["type"] = "member"; Response.Redirect("~/MemberPages/Member.aspx"); } else { LoginErrorLbl.Text = "Invalid credentials!"; } } catch { LoginErrorLbl.Text = "Invalid credentials!"; } }
protected void LogInButton_Click(object sender, EventArgs e) { try { //Create object of Crypto class CryptoClass crypto = new CryptoClass(); String id = UserNameTb.Text; //Encrypt the password String password = crypto.Encrypt(PasswordTb.Text); //Create object of reference class Assignment5ServiceRefs.Service1Client serviceRef = new Assignment5ServiceRefs.Service1Client(); //get the role from the Staff.xml string role = serviceRef.checkUserCredentialsForStaff(id, password); //if the role is not empty if (!role.Equals("")) { //Create a cookie and store the user id HttpCookie userCookies = new HttpCookie("userInfo"); userCookies["id"] = UserNameTb.Text; //Cookie expires in 6 months userCookies.Expires = DateTime.Now.AddMonths(6); Response.Cookies.Add(userCookies); //Redirect to the staff page after authentication FormsAuthentication.RedirectFromLoginPage(UserNameTb.Text, Persistent.Checked); //Store the role in the session Session["type"] = role; userCookies["type"] = role; //If the role is staff, redirect to the staff page if (role.Equals("staff")) { Response.Redirect("~/StaffPage2/StaffPage.aspx"); } //else if the role is admin, redirect to the admin page else if (role.Equals("admin")) { Response.Redirect("~/StaffPage1/AdminPage.aspx"); } //else redirect to the public default page else { Response.Redirect("~/Default.aspx"); } } //Print error message if the credentials are invalid else { LoginErrorLbl.Text = "Invalid credentials!"; } } catch { LoginErrorLbl.Text = "Invalid credentials!"; } }
public Client2Server(string user, string password, string server, int port) { var md5 = MD5.Create(); this.userName = user; this.userPas = Encoding.Unicode.GetString(md5.ComputeHash(Encoding.Unicode.GetBytes(password))); this.host = server; this.port = port; client = new TcpClient(); client.Connect(this.host, this.port); stream = client.GetStream(); Cr = new CryptoClass(); }
// трансляция сообщения подключенным клиентам protected internal void BroadcastMessage(string message, string id) { CryptoClass enc = new CryptoClass(); for (int i = 0; i < clients.Count; i++) { if (clients[i].Id != id) // если id клиента не равно id отправляющего { string en = enc.Encrypt(message, keys[i]); byte[] data = Encoding.Unicode.GetBytes(en); clients[i].Stream.Write(data, 0, data.Length); //передача данных } } }
protected void signUpButton_Click(object sender, EventArgs e) { try { CryptoClass crypto = new CryptoClass(); Assignment5ServiceRefs.Service1Client serviceRef = new Assignment5ServiceRefs.Service1Client(); if (!UserIdTb.Text.ToString().Equals("") && !NameTb.Text.ToString().Equals("") && !PasswordTb.Text.ToString().Equals("") && !CardNoTb.Text.ToString().Equals("")) { String status = serviceRef.SignUpMembers(UserIdTb.Text, crypto.Encrypt(PasswordTb.Text), NameTb.Text, CardNoTb.Text); if (status.Equals("UserIdTaken")) { UserIdErrorLbl.Text = "User Id is already taken"; } else if (status.Equals("false")) { UserIdErrorLbl.Text = "An exception occured during sign up."; } else { Session["name"] = NameTb.Text; FormsAuthentication.RedirectFromLoginPage(NameTb.Text, true); Response.Redirect("~/MemberPages/Member"); } } else { if (UserIdTb.Text.ToString().Equals("")) { UserIdErrorLbl.Text = "User Id is required"; } if (NameTb.Text.ToString().Equals("")) { NameErrorLbl.Text = "Name is required"; } if (PasswordTb.Text.ToString().Equals("")) { PasswordErrorLbl.Text = "Password is required"; } if (CardNoTb.Text.ToString().Equals("")) { CardErrorLbl.Text = "Card Number is required"; } } } catch { UserIdErrorLbl.Text = "An exception occured during sign up."; } }
public ResponseModel <UserModel> Post([FromBody] UserModel value) { var response = new ResponseModel <UserModel>(); try { if (value == null || string.IsNullOrEmpty(value?.Email)) { response.Status = 200; response.Description = "Wrong data..."; return(response); } if (UserRepo.ExistUserByEmail(value.Email)) { response.Status = 200; response.Description = "This user already exist"; return(response); } var pass = value.Password; value.Password = CryptoClass.CreateHash(pass); var user = new User { FirstName = value.FirstName, LastName = value.LastName, Password = value.Password, Email = value.Email, IsActive = value.IsActive }; UserRepo.Insert(user); value.Id = user.Id; value.Password = null; response.Status = 200; response.Description = "OK"; response.Data = value; } catch (Exception ex) { response.Status = 500; response.Description = $"Critical error: {ex.Message}"; response.Data = null; } return(response); }
private void Select_Click(object sender, RoutedEventArgs e) { OpenFileDialog openFile = new OpenFileDialog() { Title = "Key Selector", DefaultExt = "hex", Filter = "Keyfile (.hex)|*.hex" }; if (openFile.ShowDialog().Value) { FileName.Content = openFile.FileName.Substring(openFile.FileName.LastIndexOf('\\') + 1); crypto = new CryptoClass(openFile.FileName); } }
private void DemoVers_StartWindows() { CryptoClass CryptoClass_ = new CryptoClass(); thisDemo = CryptoClass_.Form_LoadTrue(true); if (thisDemo) { this.Text = $"{Application.ProductName} v{Application.ProductVersion} {Body.KompasVersionFlag} !!!This DemoVersion!!!"; Licence_Manager_ribbonPageGroup1.Visible = true; } else { this.Text = $"{Application.ProductName} v{Application.ProductVersion} {Body.KompasVersionFlag}"; Licence_Manager_ribbonPageGroup1.Visible = false; } }
private void Create_Click(object sender, RoutedEventArgs e) { SaveFileDialog saveFile = new SaveFileDialog() { Title = "Key Generator", DefaultExt = "hex", Filter = "Keyfile (.hex)|*.hex" }; if (saveFile.ShowDialog().Value) { BytesGenerator.KeyFileGenerator(saveFile.FileName, 56); FileName.Content = saveFile.FileName.Substring(saveFile.FileName.LastIndexOf('\\') + 1); crypto = new CryptoClass(saveFile.FileName); } }
void Start() { cc = new CryptoClass(); Debug.Log(cc.GetCode(100, 100)); groundMaterial = GameObject.Find("Ground").GetComponent <Renderer> ().material; mainLight = GameObject.Find("Directional Light"); RandomizeGroundColor(); RandomizeLighting(); descriptionText.text = ""; controlText.text = ""; puc = GameObject.Find("PlayerUnit").GetComponent <PlayerUnitController> (); playerUnit = puc.GetComponent <Unit> (); coverPanel = GameObject.Find("CoverPanel").GetComponent <Image> (); coverPanel.color = Color.black; puc.active = false; FadeFromBlack(); }
protected internal void PrivateMessage(string polname, string otprname, string message)//личка { CryptoClass enc = new CryptoClass(); if (message != "") { message = otprname + ":" + message; } else { message = otprname; } int i = usernames.IndexOf(polname); Console.WriteLine(message); string en = enc.Encrypt(message, keys[i]); byte[] data = Encoding.Unicode.GetBytes(en); clients[i].Stream.Write(data, 0, data.Length); }
public bool GetKeys() { try { CryptoClass cc = new CryptoClass(); var fileName = "keyfile.key"; var GetKeys = cc.DecryptMethod(fileName).Split(','); this.accountSID = GetKeys[0].Trim(); this.authorizationToken = GetKeys[1].Trim(); this.CallerIDNumber1 = GetKeys[2].Trim(); this.CallerIDNumber2 = GetKeys[3].Trim(); this.uri1 = GetKeys[4].Trim(); this.uri2 = GetKeys[5].Trim(); return(true); } catch { return(false); } }
private static Task <ClaimsIdentity> GetIdentity(string email, string password) { IUserRepository userRepo = new UserRepository(new DataBaseContext()); var user = userRepo.GetActiveUserByEmailWithPass(email); if (user == null) { return(Task.FromResult <ClaimsIdentity>(null)); } if (CryptoClass.CheckPassword(password, user.Password)) { var identity = new ClaimsIdentity(new GenericIdentity(user.Id.ToString(), "Token")); identity.AddClaim(new Claim("userId", (user?.Id ?? 0).ToString())); identity.AddClaim(new Claim("userMail", user.Email)); //identity.AddClaim(new Claim("refreshToken", user.Email)); return(Task.FromResult(identity)); } return(Task.FromResult <ClaimsIdentity>(null)); }
private void btnLoad_Click(object sender, EventArgs e) { if (boxToken.Text == "") { MessageBox.Show("Заполните токен!"); return; } ThisAddIn.token = boxToken.Text; // Шифруем токен byte[] Encrypted_Bytes = CryptoClass.encrypt_function(ThisAddIn.token); // Записывем токен в реестр if ((ThisAddIn.keyName != null) && (ThisAddIn.keyName != "")) { Registry.SetValue(ThisAddIn.keyName, "Token", Encrypted_Bytes); MessageBox.Show("Токен зашифрован и безопасно сохранен для последующих запусков!"); } this.DialogResult = DialogResult.OK; this.Close(); }
private static void UsersRecords(DataBaseContext context) { if (context.Users.Any()) { return; } var users = new User { Id = 1, Email = "*****@*****.**", FirstName = "test", LastName = "test", Password = CryptoClass.CreateHash("test"), Date = DateTime.Now, IsActive = true, IsDelete = false }; context.Users.Add(users); context.SaveChanges(); }
private async Task FillList(string filePath, CryptoClass crypto) { CancellationToken token; try { CancellationTokenSource tokenSource = new CancellationTokenSource(); token = tokenSource.Token; progressBar = new Progress(); progressBar.ProgressBar1.IsIndeterminate = true; progressBar.Show(); progressBar.Closing += (object sender, CancelEventArgs e) => { tokenSource.Cancel(); }; EventRaiser.OnFileNameChange += Unpacker_OnProgressFileNameEvent; EventRaiser.OnProgressChange += Unpacker_OnProgressPercentEvent; unpacker = await Task.Run(() => new FileUnpacker(filePath, crypto, token)); Stream unpackerStream = unpacker.UnpackStream(unpacker.fileDatas[0]); ListInit(filePath); } catch (NotAnOOFPackException) { progressBar?.Close(); MessageBox.Show("Invalid or corrupted OOF Pack!", "OOF GUI", MessageBoxButton.OK, MessageBoxImage.Warning); } catch (InvalidHeaderException e) { progressBar?.Close(); MessageBox.Show("Corrupted OOF Pack! " + e.Message, "OOF GUI", MessageBoxButton.OK, MessageBoxImage.Warning); } catch (ThreadAbortException) { progressBar?.Close(); } catch (EncryptedException) { progressBar?.Close(); OpenFileDialog selectKeyDialog = SelectKeyDialog("Your Pack seems to be encrypted! Please select a Keyfile to decrypt it."); if (selectKeyDialog != null && selectKeyDialog.ShowDialog().Value) { await FillList(filePath, new CryptoClass(selectKeyDialog.FileName)); } } catch (IncorrectKeyException) { progressBar?.Close(); OpenFileDialog selectKeyDialog = SelectKeyDialog("The Key seems to be wrong or corrupted. Please select the correct decryption keyfile!"); if (selectKeyDialog != null && selectKeyDialog.ShowDialog().Value) { await FillList(filePath, new CryptoClass(selectKeyDialog.FileName)); } } catch (Exception e) { progressBar?.Close(); MessageBox.Show("Something went wrong! " + e.Message, "OOF GUI", MessageBoxButton.OK, MessageBoxImage.Error); } finally { progressBar?.Close(); } }
public ResponseModel <bool> EditUser([FromBody] UserModel userModel) { var response = new ResponseModel <bool>(); try { if (userModel == null) { response.Status = 200; response.Description = "Wrong data..."; response.Data = false; return(response); } var user = UserRepo.GetById(userModel?.Id ?? 0); if (user == null) { throw new Exception("User not found"); } if (!user.Password.Equals(CryptoClass.CreateHash(userModel.OldPassword))) { throw new Exception("User's password is incorrect"); } if (!string.IsNullOrEmpty(userModel.Password)) { user.Password = CryptoClass.CreateHash(userModel.Password); } user.IsDelete = userModel.IsDelete; user.IsActive = userModel.IsActive; if (userModel.Email != null) { user.Email = userModel.Email; } if (userModel.FirstName != null) { user.FirstName = userModel.FirstName; } if (userModel.LastName != null) { user.LastName = userModel.LastName; } if (UserRepo.Update(user)) { response.Status = 200; response.Description = "OK"; response.Data = true; return(response); } response.Status = 500; response.Description = "Error"; response.Data = false; return(response); } catch (Exception ex) { response.Status = 500; response.Description = $"Critical error: {ex.Message}"; response.Data = false; return(response); } }
public static string GetSetting(string s) { string result = CryptoClass.DESDecrypt(s, "12345678"); return(result); }
public void TestInitialize() { form = new Form1(); testCrypto = new CryptoClass(); Directory.SetCurrentDirectory(@"C:\Users\alexh\documents"); }
private string GenerateToken(GroupInvitations hash) { return(CryptoClass.CreateHash(GetTokenHash(hash))); }
public void Process() { try { Stream = client.GetStream(); // получаем имя пользователя string message = GetMessage(); if (message[0] == '1') //регистрация { message = message.Remove(0, 1); if (!FileWrite(message).Result) //отклонение регистрации { byte[] reject = Encoding.Unicode.GetBytes("0"); Stream.Write(reject, 0, reject.Length); } } if (message[0] == '2') //авторизация { message = message.Remove(0, 1); if (FileRead(message).Result == 2) //обработать несколько юзеров с одним ником { CryptoClass enc = new CryptoClass(); key = enc.GetStringKey(); //генерация ключа server.Keys(key); Console.WriteLine(key); string keymess = "6" + key; byte[] keym = Encoding.Unicode.GetBytes(keymess); Stream.Write(keym, 0, keym.Length); //отправка ключа string[] name = message.Split(';'); //список юзеров userName = name[0]; user = userName; message = "8" + userName;//connect // посылаем сообщение о входе в чат всем подключенным пользователям server.BroadcastMessage(message, this.Id); //список всех юзеров для новоприбывшего string snames = "7"; server.Usernames(user); List <string> unames = server.Usrnms; for (int i = 0; i < unames.Count; i++) { snames += unames[i] + ";"; } snames = snames.Remove(snames.Length - 1); snames = enc.Encrypt(snames, key); byte[] lnames = Encoding.Unicode.GetBytes(snames); Stream.Write(lnames, 0, lnames.Length); Console.WriteLine(message.Remove(0, 1) + " вошёл в чат"); string[] info = new string[3]; //0 получатель файла, 1 имя.расширение файла, 2 размер файла while (true) //обмен сообщениями { try { message = GetMessage(); message = enc.Decrypt(message, key); if (message[0] == '3')//обычное сообщение { message = message.Remove(0, 1); message = String.Format("3" + userName + ":" + message); Console.WriteLine(message); server.BroadcastMessage(message, this.Id); } if (message[0] == '4')//личка { message = message.Remove(0, 1); string PrivateMsg = message.Substring(message.IndexOf(':') + 1); string PrivateName = message.Substring(0, message.IndexOf(':')); Console.WriteLine(this.userName + " для " + PrivateName + ": " + PrivateMsg); server.PrivateMessage(PrivateName, "4" + this.userName, PrivateMsg); } if (message[0] == 'h')//заголовок файла { message = message.Remove(0, 1); info = message.Split(':'); Console.WriteLine("файл от " + this.userName + " для " + info[0] + ": " + info[1] + " " + info[2]); server.PrivateMessage(info[0], "h" + this.userName, info[1] + ":" + info[2]); } if (message[0] == 'a')//принял передачу { message = message.Remove(0, 1); message = RemoveNulls(message); Console.WriteLine(this.userName + " принял файл от " + message); server.PrivateMessage(message, "a" + this.userName, ""); } if (message[0] == 'r')//отклонил передачу { message = message.Remove(0, 1); message = RemoveNulls(message); Console.WriteLine(this.userName + " отклонил файл от " + message); server.PrivateMessage(message, "r" + this.userName, ""); } if (message[0] == 'f')//приём файла { Console.WriteLine("прием"); message = message.Remove(0, 1); //message = RemoveKosyak(message); GetFile(info[1], message); } if (message[0] == 's')//приём файла { Console.WriteLine("отправка"); SendFile(info[0], info[1]); File.Delete(info[1]); } } catch { message = String.Format("9" + userName);//disconnect Console.WriteLine(message.Remove(0, 1) + " покинул чат"); server.BroadcastMessage(message, this.Id); break; } } } } // в бесконечном цикле получаем сообщения от клиента } catch (Exception e) { Console.WriteLine(e.Message); } finally { // в случае выхода из цикла закрываем ресурсы server.RemoveConnection(this.Id); Close(); } }