public void SaltedHashTest_Negative(string password) { SaltedHash hasher = new SaltedHash(password); var salt = '+' + hasher.Salt; Assert.False(SaltedHash.Verify(password, hasher.Hash, salt)); }
public ActionResult Details(UserProfileViewModel model) { if (ModelState.IsValid) { // get user info var user = Context.Users.Where(u => u.UserId == model.UserId).FirstOrDefault(); if (user == null) { return(HttpNotFound(String.Format("Tài khoản #{0} không tồn tại", model.UserId))); } // verify current password if (!SaltedHash.Verify(user.Salt, user.Password, model.CurrentPassword)) { ModelState.AddModelError("", "Mật khẩu hiện tại không hợp lệ"); return(View(model)); } // update user password SaltedHash sh = new SaltedHash(model.Password); user.Password = sh.Hash; user.Salt = sh.Salt; Context.SaveChanges(); FormsAuthentication.SignOut(); return(RedirectToAction("Login", "User")); } else { ModelState.AddModelError("", "Dữ liệu không hợp lệ"); return(View(model)); } }
public ActionResult Login(LoginViewModel model) { var actionLogData = ""; try { if (ModelState.IsValid) { // get user info var userLogin = db.Users.Where(u => String.Compare(u.Username, model.UserName, true) == 0).FirstOrDefault(); if (userLogin != null) { // verify user password var loginSuccess = SaltedHash.Verify(userLogin.Salt, userLogin.Password, model.Password); if (loginSuccess) { BizManPrincipalSerialize principal = new BizManPrincipalSerialize(); principal.UserId = userLogin.UserId; principal.FirstName = userLogin.FirstName; principal.LastName = userLogin.LastName; principal.CreationDate = userLogin.CreateDate; principal.Roles = userLogin.Roles.Select(r => r.RoleName).ToArray(); string jsonPrincipal = JsonConvert.SerializeObject(principal); FormsAuthenticationTicket ticket = new FormsAuthenticationTicket( 1, userLogin.Username, DateTime.Now, DateTime.Now.AddDays(7), model.RememberMe, jsonPrincipal); string ticketEncrypted = FormsAuthentication.Encrypt(ticket); HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, ticketEncrypted); Response.Cookies.Add(faCookie); // Write action log actionLogData = "user:"******", success"; ActionLog.WriteLog(ActionLog.LOGIN, actionLogData, userLogin.Username, Request.ServerVariables["REMOTE_ADDR"]); return(RedirectToAction("Index", "Home")); } } } ModelState.AddModelError("", "Sai tên đăng nhập hoặc mật khẩu!"); } catch (Exception ex) { ModelState.AddModelError("", ex.Message); } // Write action log actionLogData = "user:"******", fail"; ActionLog.WriteLog(ActionLog.LOGIN, actionLogData, model.UserName, Request.ServerVariables["REMOTE_ADDR"]); return(View(model)); }
public ActionResult ChangePass(ChangePassViewModel model) { try { if (ModelState.IsValid) { // get current user info var userInfo = db.Users.Where(u => u.UserId == model.UserId).FirstOrDefault(); if (userInfo == null) { return(RedirectToAction("Login", "Auth")); } // verify old password var isCorrectOldPass = SaltedHash.Verify(userInfo.Salt, userInfo.Password, model.OldPassword); if (isCorrectOldPass) { // new password must be different to old passowrd if (String.Compare(userInfo.Password, SaltedHash.ComputeHash(userInfo.Salt, model.NewPassword), false) != 0) { // update new user password SaltedHash sh = new SaltedHash(model.NewPassword); userInfo.Salt = sh.Salt; userInfo.Password = sh.Hash; userInfo.FirstName = model.FirstName; userInfo.LastName = model.LastName; userInfo.Email = model.Email; db.SaveChanges(); // write action log string actionLogData = "username="******"REMOTE_ADDR"]); return(RedirectToAction("Index", "Home")); } else { ModelState.AddModelError("", "Mật khẩu mới không được trùng mật khẩu cũ"); } } else { ModelState.AddModelError("", "Mật khẩu cũ chưa chính xác"); } } else { ModelState.AddModelError("", "Thông tin đổi mật khẩu không hợp lệ!"); } } catch (Exception ex) { ModelState.AddModelError("", ex.Message); } return(View(model)); }
public void Verify_salted_password_is_verified() { for (var i = 0; i < 50; i++) { var password = PasswordGenerator.Generate(32); var saltedHash = SaltedHash.Compute(password); Assert.True(SaltedHash.Verify(password, saltedHash.Hash, saltedHash.Salt)); } }
public void Verify_salted_password_is_verified() { for (int i = 0; i < 50; i++) { string password = PasswordGenerator.Generate(32); SaltedHash saltedHash = SaltedHash.Compute(password); Assert.True(SaltedHash.Verify(password, saltedHash.PasswordHash, saltedHash.Salt)); } }
private void SignInButton_Click(object sender, EventArgs e) { Connect connect = Connect.GetInstance(); SqlCommand passCommand = new SqlCommand(); SqlDataReader reader; string hash = ""; string salt = ""; string mail = ""; string passSqlQuery = "select email, password, salt from Users where email = @mail"; connect.OpenConnection(); passCommand.CommandText = passSqlQuery; passCommand.Connection = connect.GetConnection(); passCommand.Parameters.Add("@mail", SqlDbType.VarChar).Value = EmailTextBox.Text; reader = passCommand.ExecuteReader(); while (reader.Read()) { mail = Convert.ToString(reader["email"]); hash = Convert.ToString(reader["password"]); salt = Convert.ToString(reader["salt"]); } reader.Close(); if (mail == EmailTextBox.Text && SaltedHash.Verify(salt, hash, PasswordTextBox.Text)) { OrdinaryUser user = new OrdinaryUser(this); MainMenu mainMenu = new MainMenu(); Menu menu = new Menu(mainMenu, user); mainMenu.SetMenu(menu); this.Hide(); MessageBox.Show("Welcome to the MoneyManager2020!", "Success"); mainMenu.Show(); connect.CloseConnection(); } else { connect.CloseConnection(); if (EmailTextBox.Text.Trim().Equals("")) { MessageBox.Show("Enter your email", "Email field is empty", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else if (PasswordTextBox.Text.Trim().Equals("")) { MessageBox.Show("Enter your password", "Password field is empty", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else { MessageBox.Show("Wrong email or password", "Invalid data", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } }
public ActionResult Login(Login model) { if (ModelState.IsValid) { var user = db.Users.Where(u => String.Compare(u.UserName, model.UserName) == 0).FirstOrDefault(); if (user != null) { if (user.IsActive) { // Verify user password var success = SaltedHash.Verify(user.Salt, user.Password, model.Password); if (success) { // Save authentication info ElectricalShopPrincipleModel principle = new ElectricalShopPrincipleModel(); principle.UserId = user.UserId; principle.FullName = user.FullName; principle.Roles = user.Roles.Select(r => r.RoleName).ToArray(); // Add authentication cookie FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, model.UserName, DateTime.Now, DateTime.Now.AddDays(7), model.RememberMe, JsonConvert.SerializeObject(principle)); String authTicketEncrypted = FormsAuthentication.Encrypt(authTicket); HttpCookie asCookie = new HttpCookie(FormsAuthentication.FormsCookieName, authTicketEncrypted); Response.Cookies.Add(asCookie); // Write action log Log log = new Log(); log.LogDate = DateTime.Now; log.Action = "Login"; log.Tags = GetRequestedIP() + "," + model.UserName; log.Message = "Đăng nhập hệ thống"; LogWritter.WriteLog(log); return(RedirectToAction("Index", "Admin")); } else { ModelState.AddModelError("", "Sai mật khẩu!"); } } else { ModelState.AddModelError("", "Tài khoản đã bị khóa!"); } } else { ModelState.AddModelError("", "Tài khoản không tồn tại trong hệ thống!"); } } return(View(model)); }
public ActionResult Profiler(Profiler model) { if (ModelState.IsValid) { var user = db.Users.Where(u => u.UserId == model.UserId).FirstOrDefault(); if (user != null) { if (String.IsNullOrWhiteSpace(model.NewPassword)) { user.FullName = model.FullName; user.Phone = model.Phone; user.Email = model.Email; db.SaveChanges(); RedirectToAction("Index", "Admin"); } else { /* User changed password */ if (SaltedHash.Verify(user.Salt, user.Password, model.Password)) { SaltedHash sh = new SaltedHash(model.NewPassword); user.Password = sh.Hash; user.Salt = sh.Salt; user.FullName = model.FullName; user.Phone = model.Phone; user.Email = model.Email; db.SaveChanges(); // Write action log Log log = new Log(); log.LogDate = DateTime.Now; log.Action = "Update profile"; log.Tags = GetRequestedIP() + "," + model.UserName; log.Message = "Cập nhật thông tin cá nhân"; LogWritter.WriteLog(log); RedirectToAction("Index", "Admin"); } else { ModelState.AddModelError("", "Sai mật khẩu!"); } } } else { return(RedirectToAction("Login")); } } return(View(model)); }
/// <summary> /// verifies the password hash of a user /// </summary> /// <param name="user">the user</param> /// <param name="hashedPassword">the password hash of the user</param> /// <param name="providedPassword">the provided password</param> /// <returns>if the provided password matches the password hash</returns> public PasswordVerificationResult VerifyHashedPassword( UserIdentityData user, string hashedPassword, string providedPassword) { if (user == null) { throw new ArgumentNullException(nameof(user)); } var saltedHash = new SaltedHash(user.PasswordSalt, hashedPassword); return(saltedHash.Verify(providedPassword) ? PasswordVerificationResult.Success : PasswordVerificationResult.Failed); }
private void TimerOnTick(object sender, object o) { _timer.Stop(); if (SelectedUser == null) { return; } if (SaltedHash.Verify(SelectedUser.Salt, SelectedUser.Hash, SelectedUser.EnteredPassword)) { UserContext.Current.Authenticate(SelectedUser.Name, SelectedUser.EnteredPassword, SelectedUser.Id, null); var rootFrame = Window.Current.Content as Frame; rootFrame.Navigate(typeof(MyAssets)); } }
public static Tuple <HumanPlayer, bool> LoadPlayer(string id, string pw) { var con = new SQLiteConnection("Data Source=DatabaseTicTacTorus.dat"); HumanPlayer player = null; SaltedHash sh = null; con.Open(); var command = new SQLiteCommand(con) { CommandText = $"select * from User where loginName ='" + id + "'" }; var reader = command.ExecuteReader(); while (reader.Read()) { player = new HumanPlayer { ID = reader[0] as string, Salt = reader[1] as byte[], Hash = reader[2] as byte[], InGameName = reader[3] as string, PlrColor = Color.FromArgb(Convert.ToInt32(reader[6])) }; //player.Symbol = (byte) reader[7]; sh = new SaltedHash(player.Salt, player.Hash); //player.Email = reader[4] as string; //player.Pic = reader[5] as Image; //funktioniert nicht wegen image } //Checks if Password is correct if (player != null && sh.Verify(pw)) { con.Close(); return(Tuple.Create(player, true)); } con.Close(); return(Tuple.Create(player, false)); }
public ActionResult Login(UserLoginViewModel model) { // Get user info var user = Context.Users .Where(u => u.Username == model.Username) .FirstOrDefault(); // Verify password if (user != null && SaltedHash.Verify(user.Salt, user.Password, model.Password)) { var roles = user.Roles.Select(r => r.RoleName).ToArray(); CoffeeShopPrincipalSerializeModel serializeModel = new CoffeeShopPrincipalSerializeModel(); serializeModel.UserId = user.UserId; serializeModel.FirstName = user.FirstName; serializeModel.LastName = user.LastName; serializeModel.Roles = roles; string userData = JsonConvert.SerializeObject(serializeModel); FormsAuthenticationTicket ticket = new FormsAuthenticationTicket( 1, user.Username, DateTime.Now, DateTime.Now.AddHours(24), model.RememberMe, userData); string encTicket = FormsAuthentication.Encrypt(ticket); HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket); Response.Cookies.Add(faCookie); return(RedirectToAction("Index", "Finance")); } else { ModelState.AddModelError("", "Sai tên đăng nhập hoặc mật khẩu!"); return(View(model)); } }
public ActionResult ChangePass(ChangePassModel model) { try { if (ModelState.IsValid) { // Get user var user = db.Users.Where(r => r.UserId == model.UserId).FirstOrDefault(); if (user != null) { // Validate current password if (SaltedHash.Verify(user.Salt, user.Password, model.PasswordCurrent)) { // Change password var sh = new SaltedHash(model.PasswordNew); user.Salt = sh.Salt; user.Password = sh.Hash; db.SaveChanges(); return(RedirectToAction("ChangePassSuccess", "Auth")); } else { ModelState.AddModelError("", "Mật khẩu hiện tại không đúng"); } } else { return(RedirectToAction("SignOut")); } } } catch (Exception ex) { ModelState.AddModelError("", ex.Message); EventWriter.WriteEventLog("AuthController - ChangePass: " + ex.ToString()); } return(View(model)); }
public ActionResult Login(LoginViewModel model) { /* * User submitted login info */ try { // validate login info if (ModelState.IsValid == false) { ModelState.AddModelError("", "Thông tin đăng nhập không hợp lệ"); return(View(model)); } // get current user info User userInfo = db.Users .Where(u => u.Username.Equals(model.UserName.Trim(), StringComparison.OrdinalIgnoreCase)) .FirstOrDefault(); if (userInfo == null) { ModelState.AddModelError("", "Đăng nhập thất bại!<p />Tên tài khoản/mật khẩu không đúng"); return(View(model)); } // verify user name and password bool loginSuccess = SaltedHash.Verify(userInfo.Salt, userInfo.Password, model.Password); if (loginSuccess) { // save authentication info DrCleanCarePrincipalSerializeModel principal = new DrCleanCarePrincipalSerializeModel(); principal.UserId = userInfo.UserId; principal.FirstName = userInfo.FirstName; principal.LastName = userInfo.LastName; principal.Roles = userInfo.Roles.Select(r => r.RoleName).ToArray(); string principalJson = JsonConvert.SerializeObject(principal); FormsAuthenticationTicket ticket = new FormsAuthenticationTicket( 1, userInfo.Username, DateTime.Now, DateTime.Now.AddHours(168), // 7 days model.RememberMe, principalJson); string encTicket = FormsAuthentication.Encrypt(ticket); HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket); Response.Cookies.Add(faCookie); return(RedirectToAction("Index", "Admin")); } else { ModelState.AddModelError(string.Empty, "Đăng nhập thất bại!<p />Tên tài khoản/mật khẩu không đúng"); return(View(model)); } } catch (ArgumentException ex) { ModelState.AddModelError(string.Empty, ex.Message); return(View(model)); } catch (NotImplementedException ex) { ModelState.AddModelError(string.Empty, ex.Message); return(View(model)); } }
public void SaltedHashTest_Positive(string password) { SaltedHash hasher = new SaltedHash(password); Assert.True(SaltedHash.Verify(password, hasher.Hash, hasher.Salt)); }
public bool Authenticate(string emailOrlogin, string password) { var account = _accountQueryService.GetByEmailOrLogin(emailOrlogin); return(account != null && SaltedHash.Verify(password, account.PasswordHash, account.PasswordSalt)); }
public HttpResponseMessage changePassword([FromBody] JObject json) { var eventLogs = ""; try { /** * Description * Input * + phone: Số điện thoai khách hàng * + passwordCurrent: Mật khẩu hiện tại * + password: Mật khẩu mới * * Output * + Success: true/false * + Data: Mô tả kết quả trả về * */ // Get requested params var phone = (json.GetValue("phone").Value <string>() ?? "").Trim(); var passwordCurrent = (json.GetValue("passwordCurrent").Value <string>() ?? "").Trim(); var password = (json.GetValue("password").Value <string>() ?? "").Trim(); var customer = db.Customers.Where(r => r.phone.Equals(phone)).FirstOrDefault(); if (customer != null) { // Verify password var success = SaltedHash.Verify(customer.salt, customer.password, passwordCurrent); if (success) { // Assign new password var sh = new SaltedHash(password); customer.salt = sh.Salt; customer.password = sh.Hash; db.SaveChanges(); return(Request.CreateResponse(HttpStatusCode.OK, new { Success = true, Data = "Đổi mật khẩu thành công!" })); } else { // Wrong password return(Request.CreateResponse(HttpStatusCode.OK, new { Success = false, Data = "Đổi mật khẩu thất bại! Mật khẩu hiện tại không đúng" })); } } else { // Customer not found return(Request.CreateResponse(HttpStatusCode.OK, new { Success = false, Data = "Đổi mật khẩu thất bại! Khách hàng #" + phone + " không tồn tại trong hệ thống!" })); } } catch (Exception ex) { // set event logs eventLogs = "CustomerController - changePassword: " + ex.ToString(); return(Request.CreateResponse(HttpStatusCode.OK, new { Success = false, Data = ex.ToString() })); } finally { // write event logs if (string.IsNullOrWhiteSpace(eventLogs) == false) { EventWriter.WriteEventLog(eventLogs); } } }
public HttpResponseMessage verify([FromBody] JObject json) { var eventLogs = ""; try { /** * Description * Input * + phone: Số điện thoai khách hàng * + password: Địa chỉ email khách hàng * * Output * + Thông tin customer * */ // Get requested params var phone = (json.GetValue("phone").Value <string>() ?? "").Trim(); var password = (json.GetValue("password").Value <string>() ?? "").Trim(); var customer = db.Database.SqlQuery <Customer>("EXEC [dbo].[usp_getCustomer] @phone", new SqlParameter("phone", phone)).FirstOrDefault(); if (customer != null) { // Verify password var success = SaltedHash.Verify(customer.salt, customer.password, password); if (success) { // set event logs eventLogs += "Login phone number = " + phone + " success"; return(Request.CreateResponse(HttpStatusCode.OK, new { Success = true, Data = new { phone = customer.phone, fullname = customer.fullname, email = customer.email, address = customer.address } })); } else { // set event logs eventLogs += "Login phone number = " + phone + " fail, wrong password"; return(Request.CreateResponse(HttpStatusCode.OK, new { Success = false, Data = "Đăng nhập thất bại! Vui lòng kiểm tra lại mật khẩu" })); } } else { // set event logs eventLogs += "Login phone number = " + phone + " fail, wrong phone number"; return(Request.CreateResponse(HttpStatusCode.OK, new { Success = false, Data = "Đăng nhập thất bại! Số điện thoại chưa được đăng ký" })); } } catch (Exception ex) { // set event logs eventLogs = "CustomerController - verify: " + ex.ToString(); return(Request.CreateResponse(HttpStatusCode.OK, new { Success = false, Data = ex.ToString() })); } finally { // write event logs if (string.IsNullOrWhiteSpace(eventLogs) == false) { EventWriter.WriteEventLog(eventLogs); } } }
public ActionResult SignIn(SignInModel model) { var eventLogs = ""; try { if (ModelState.IsValid) { eventLogs += "Login, user:"******", success"; return(RedirectToAction("Index", "Admin")); } else { eventLogs += ", fail, wrong password"; ModelState.AddModelError("", "Sai mật khẩu"); } } else { eventLogs += ", fail, invalid user"; ModelState.AddModelError("", "Sai tên tài khoản"); } } } catch (Exception ex) { // set error ModelState.AddModelError("", ex.Message); // write error log eventLogs += "error: " + ex.Message; } finally { // Write event log if (!string.IsNullOrWhiteSpace(eventLogs)) { EventWriter.WriteEventLog(eventLogs); } } return(View(model)); }