public bool AddNewCustomerAccount(CustomerAccount model) { string encryptedPassword = BCryptHelper.HashPassword(model.Password, BCryptHelper.GenerateSalt(6)); model.Password = encryptedPassword; return(Repository.AddNewCustomerAccount(model)); }
public IActionResult ForgotPassword(ForgotPasswordViewModel model) { if (!ModelState.IsValid) { return(View(model)); } var user = this._context.Users.FirstOrDefault(u => u.EmailAddress.ToLower() == model.EmailAddress.ToLower()); if (user != null) { var newPassword = RandomString(9); user.Password = BCryptHelper.HashPassword(newPassword, BCryptHelper.GenerateSalt(9)); user.LoginStatus = Infrastructures.Domain.Enums.LoginStatus.Active; this._context.Users.Update(user); this._context.SaveChanges(); this.EmailSendNow( ForgotPasswordEmailTemplate(newPassword, user.UserName), user.EmailAddress, user.UserName, "Fixit.ph Website - Forgot Password" ); return(RedirectToAction("OTP")); } ModelState.AddModelError("", "Email-Address does'nt exist!"); return(View(model)); }
public IActionResult ResetPassword(Guid?userId) { var user = this._context.Users.FirstOrDefault(u => u.Id == userId); if (user != null) { var password = RandomString(8); user.Password = BCryptHelper.HashPassword(password, BCryptHelper.GenerateSalt(9)); user.LoginStatus = Infrastructures.Domain.Enums.LoginStatus.NeedToChangePassword; this._context.Users.Update(user); this._context.SaveChanges(); this.EmailSendNow( ResetPasswordEmailTemplate(password, user.UserName), user.EmailAddress, user.UserName, "CarWashBookings.Ph - Password Reset" ); //this.SMSSendNow("Your password has been reset by an Admin. Please use this one-time password : "******" to login to the system.", user.PhoneNumber); } return(RedirectToAction("index")); }
/// <summary> /// Hashing Password /// </summary> /// <param name="plainTextPassword"></param> /// <returns></returns> public string GetPasswordHash(string plainTextPassword) { string salt = BCryptHelper.GenerateSalt(); string hashedPassword = BCryptHelper.HashPassword(plainTextPassword, salt); return(hashedPassword); }
public ActionResult Register(RegisterModel model) { if (model == null) { ViewBag.LoginError = "Hatalı kullanıcı adı ya da şifre!"; return(RedirectToAction("Login")); } else { using (var ctx = new IFSAppContext()) { var u = ctx.Users.Where(w => w.Username == model.Username).SingleOrDefault(); if (u != null) { ViewBag.RegisterError = "Kullanıcı adı mevcut"; return(RedirectToAction("Login")); } UserModel user = new UserModel() { DefaultCityName = model.DefaultCityName, Name = model.Name, Username = model.Username, Password = BCryptHelper.HashPassword(model.Password, BCryptHelper.GenerateSalt(12)), UserType = "Son Kullanıcı", Status = 1, }; ctx.Users.Add(user); ctx.SaveChanges(); return(RedirectToAction("Login")); } } }
private string HashPassword(string password) { var salt = BCryptHelper.GenerateSalt(); var hashedPassword = BCryptHelper.HashPassword(password, salt); return(hashedPassword); }
public IActionResult ChangePassword(ChangePasswordViewModel model) { if (model.NewPassword != model.ConfirmNewPassword) { ModelState.AddModelError("", "New Password does not match Confirm New Password"); return(View()); } var user = this._context.Users.FirstOrDefault(u => u.Id == model.UserId); if (user != null) { if (BCryptHelper.CheckPassword(model.OldPassword, user.Password) == false) { ModelState.AddModelError("", "Incorrect old Password."); return(View()); } user.Password = BCryptHelper.HashPassword(model.NewPassword, BCryptHelper.GenerateSalt(8)); user.LoginStatus = Infrastructures.Domain.Enums.LoginStatus.Active; this._context.Users.Update(user); this._context.SaveChanges(); return(RedirectPermanent("Notify")); } return(View()); }
public async static Task <int> RegisterPlayer(string username, string password, string email, string socialName, string ip) { if (await CheckIfPlayerRegistered(username)) { return(0); } else { using (MySqlConnection connection = new MySqlConnection(Data.DatabaseHandler.connectionHandle)) { await connection.OpenAsync().ConfigureAwait(false); MySqlCommand command = connection.CreateCommand(); string pSalt = BCryptHelper.GenerateSalt(); string pEncrypt = BCryptHelper.HashPassword(password, pSalt); command.CommandText = "INSERT INTO users (name, password, salt, email, socialName, ip) VALUES (@username, @password, @salt, @email, @socialName, @ip)"; command.Parameters.AddWithValue("@username", username); command.Parameters.AddWithValue("@password", pEncrypt); command.Parameters.AddWithValue("@salt", pSalt); command.Parameters.AddWithValue("@email", email); command.Parameters.AddWithValue("@socialName", socialName); command.Parameters.AddWithValue("@ip", ip); await command.ExecuteNonQueryAsync().ConfigureAwait(false); return((int)command.LastInsertedId); } } }
public ActionResult Register(Users users) { try { string password = users.Password; string salt = BCryptHelper.GenerateSalt(7); string hashedPassword = BCryptHelper.HashPassword(password, salt); string verifyCode = BCryptHelper.GenerateSalt(5); users.Password = hashedPassword; users.Salt = salt; users.Active = 0; users.verifyCode = verifyCode; db.Users.Add(users); db.SaveChanges(); TempData["Email"] = users.Email; TempData["verifyCode"] = users.verifyCode; TempData["Action"] = "Register"; return(RedirectToAction("Email", "Account")); } catch { TempData["Type"] = "Danger"; TempData["Message"] = "Registration failed! Email already in use!"; return(View()); } }
public ActionResult resetPassword(string email, Users users) { try { string resetCode = BCryptHelper.GenerateSalt(5); var exist = db.Users.Where(x => x.Email == email.ToLower()).Single(); if (exist != null) { exist.resetCode = resetCode; db.Entry(exist).State = EntityState.Modified; db.SaveChanges(); TempData["Email"] = email; TempData["resetCode"] = resetCode; TempData["Action"] = "resetPassword"; return(RedirectToAction("Email", "Account")); } return(View()); } catch { TempData["Type"] = "Danger"; TempData["Message"] = "The email supplied doesn´t exist in our system. "; return(View()); } }
public AuthService(IHttpContextAccessor httpContextAccessor) { _httpContextAccessor = httpContextAccessor; salt = BCryptHelper.GenerateSalt(); var applicationUser = new ApplicationUser() { Id = 1, Email = "*****@*****.**", UserName = "******", FirstName = "mayur", LastName = "agarwal", PasswordHash = BCryptHelper.HashPassword("password", salt) }; var testApplicationUser = new ApplicationUser() { Id = 2, Email = "*****@*****.**", UserName = "******", FirstName = "test", LastName = "test", PasswordHash = BCryptHelper.HashPassword("test", salt) }; _applicationUsers = new Dictionary <string, ApplicationUser>() { { "mayur", applicationUser }, { "test", testApplicationUser } }; }
private string GenerateEncryptedPassword(string password) { var salt = BCryptHelper.GenerateSalt(); var passwordHash = BCryptHelper.HashPassword(password, salt); return(passwordHash); }
public void RegisterAttempt(Client player, object[] arguments) { using var ctx = new DefaultDbContext(); if (ctx.Accounts.Count(t => string.Equals(t.SocialClubName, player.SocialClubName, StringComparison.CurrentCultureIgnoreCase)) != 0) { player.TriggerEvent("AuthError", "Dieser Benutzername existiert bereits."); return; } var ip = player.Address.Split('.'); var user = new AccountModel { Password = BCryptHelper.HashPassword((string)arguments[0], BCryptHelper.GenerateSalt()), Email = (string)arguments[1], SocialClubName = player.SocialClubName, Ip = $"{ip[0]}.{ip[1]}.XXX.XXX", Player = player }; ctx.Accounts.Add(user); player.SetData("User", user); player.TriggerEvent("ShowCharacterSelection", new Dictionary <string, string> { { "ReadyEvent", "OnFillCharacters" }, }); ctx.SaveChanges(); }
protected void Page_Load(object sender, EventArgs e) { string secret = "P@$$w0rd"; byte[] bytes = Encoding.Unicode.GetBytes(secret); string salt = BCryptHelper.GenerateSalt(); byte[] src = Encoding.Unicode.GetBytes(salt); byte[] inArray = null; HashAlgorithm hashAlgorithm = HashAlgorithm.Create("SHA1"); byte[] buffer6 = new byte[src.Length + bytes.Length]; System.Buffer.BlockCopy(src, 0, buffer6, 0, src.Length); System.Buffer.BlockCopy(bytes, 0, buffer6, src.Length, bytes.Length); inArray = hashAlgorithm.ComputeHash(buffer6); var saltedHashedPassword = BCryptHelper.HashPassword(secret, salt); PlainTextLabel.Text = secret; SaltTextLabel.Text = salt; MD5TextLabel.Text = HexStringFromBytes(MD5.Create("MD5").ComputeHash(bytes)); SHA1TestLabel.Text = HexStringFromBytes(SHA1.Create("SHA1").ComputeHash(bytes)); SaltedSHA1TextLabel.Text = saltedHashedPassword; RFC2898TextLabel.Text = SaltAndHashPassword(secret, src, 32); }
public IHttpActionResult Register(RegisterRequest register) { try { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } //student info var student = new StudentModel() { Email = register.Email, FirstName = register.FirstName, LastName = register.LastName, PhoneNumber = register.PhoneNumber, DateOfBirth = register.DateOfBirth, EducationEndDate = register.EducationEndDate, Nationality = register.Nationality }; //password hash string mySalt = BCryptHelper.GenerateSalt(); var hashedPassword = BCryptHelper.HashPassword(register.Password, mySalt); var result = studentHandler.Create(student, hashedPassword); return(Ok("Success")); } catch (Exception) { return(Ok("Something went wrong")); } }
public string EncryptPassword(string userEnteredPassword) { userEnteredPassword += setupsConfiguration.PasswordSalt; string hash = BCryptHelper.GenerateSalt(); return(BCryptHelper.HashPassword(userEnteredPassword, hash)); }
public async Task <IActionResult> OnPostAsync() { if (string.IsNullOrEmpty(Input.NewPassword)) { Input.NewPassword = IdentityUserDefaultPwd.DefaultPassword; Input.ConfirmPassword = IdentityUserDefaultPwd.DefaultPassword; } if (!ModelState.IsValid) { return(Page()); } var user = await _userManager.GetUserAsync(User); if (user == null) { return(NotFound($"Ne peut pas charger le num's '{_userManager.GetUserId(User)}'.")); } var changePasswordResult = await _userManager.ChangePasswordAsync(user, Input.OldPassword.ToLower(), Input.NewPassword.ToLower()); if (!changePasswordResult.Succeeded) { foreach (var error in changePasswordResult.Errors) { ModelState.AddModelError(string.Empty, error.Description); } return(Page()); } // Si impossible de trouver l'utilisateur dans la BDD UserData, on annule le changement de mdp var userData = _context.UserData.Find(user.UserName); if (userData == null) { changePasswordResult = await _userManager.ChangePasswordAsync(user, Input.NewPassword.ToLower(), Input.OldPassword.ToLower()); ModelState.AddModelError(string.Empty, "Impossible de trouver l'utilisateur dans la BDD UserData."); foreach (var error in changePasswordResult.Errors) { ModelState.AddModelError(string.Empty, error.Description); } return(Page()); } userData.FoysApiHasPassword = Input.NewPassword.ToLower() != IdentityUserDefaultPwd.DefaultPassword; userData.DateDerniereModif = DateTime.Now; userData.FoysApiPasswordSalt = BCryptHelper.GenerateSalt(); userData.FoysApiPasswordHash = BCryptHelper.HashPassword(Input.NewPassword.ToLower(), userData.FoysApiPasswordSalt); _context.Attach(userData).State = EntityState.Modified; await _context.SaveChangesAsync(); await _signInManager.RefreshSignInAsync(user); return(Redirect("/pg")); }
public async Task <IdentityResponse> RegisterAsync(Users user) { var checkEmail = await _context.Users .FirstOrDefaultAsync(x => x.email == user.email); if (checkEmail != null) { return(new IdentityResponse { errors = new[] { "email already exist." } }); } var checkUsername = await _context.Users .FirstOrDefaultAsync(x => x.username == user.username); if (checkUsername != null) { return(new IdentityResponse { errors = new[] { "username already exist." } }); } string salt = BCryptHelper.GenerateSalt(10); user.password = BCryptHelper.HashPassword(user.password, salt); _context.Users.Add(user); await _context.SaveChangesAsync(); return(GenerateAuthenticationResultForUser(user)); }
public Register(string userName, string password) { string salt = BCryptHelper.GenerateSalt(); _passwordHash = BCryptHelper.HashPassword(password, salt); _userName = userName; }
private void btnRegister_Click(object sender, EventArgs e) { String username = txtLogin.Text; String password = txtPassword.Text; txtLogin.Enabled = false; txtPassword.Enabled = false; if (!String.IsNullOrWhiteSpace(username) || !String.IsNullOrWhiteSpace(password)) { String hashed = BCryptHelper.HashPassword(password, BCryptHelper.GenerateSalt()); Account account = new Account(username, hashed); if (!DefaultAccountService.createAccount(username, account)) { MessageBox.Show("Register failed, username taken."); } else { MessageBox.Show("Register succeeded."); } } else { MessageBox.Show("Invalid inputs!"); } txtLogin.Enabled = true; txtPassword.Enabled = true; txtPassword.Clear(); }
public PlayerInfo(string username, string vorname, string nachname, string password, bool loggedin) { this.username = username; this.vorname = vorname; this.nachname = nachname; this.password = BCryptHelper.HashPassword(password, BCryptHelper.GenerateSalt()); }
public void CreateUser(User user, Role role) { if (context.Users.Count() == 0 && context.Roles.Count() == 0) { // no need explaining why I use bcrypt // but in case you wonder, this is just the thread you need - https://news.ycombinator.com/item?id=4073477 string salt = BCryptHelper.GenerateSalt(10); user.Password = BCryptHelper.HashPassword(user.Password, salt); user.Salt = salt; context.Roles.Add(role); context.Users.Add(user); context.SaveChanges(); context.Users.Attach(user); context.Roles.FirstOrDefault(u => u.Name == role.Name).Users.Add(user); Profile profile = new Profile { Name = context.Blogs.FirstOrDefault().Name, User = user }; context.Profiles.Add(profile); context.SaveChanges(); } else { throw new Exception("It seems that you've already registred master user for this instance.");//"User named " + user.Username + " is already here."); } }
public void Event_Register(Client client, string login, string email, string password) { Task.Factory.StartNew(() => { try { if (!Database.ReturnEmail(email)) { string dbpassword = BCryptHelper.HashPassword(password, BCryptHelper.GenerateSalt()); Database.RegisterAccount(login, dbpassword, email, client.Address); client.TriggerEvent("RegisterResultTrue"); } else { NAPI.Util.ConsoleOutput("не рег"); client.TriggerEvent("RegisterResultFalse"); } } catch (Exception ex) { Globals.log.Trace(ex); NAPI.Util.ConsoleOutput("[EXCEPTION CreateCharacter] " + ex.Message); NAPI.Util.ConsoleOutput("[EXCEPTION CreateCharacter] " + ex.StackTrace); } }); }
public static bool Register(this SqlConnection connection, User user) { if (user == null) { throw new ArgumentNullException(nameof(user)); } if (connection.IsUnique(user)) { var sqlQuery = @"INSERT INTO [User] (Id, Nickname, Password, StatusId, LastAvailable, RegistrationDate) VALUES (@Id, @Nickname, @Password, @StatusId, @LastAvailable, @RegistrationDate)"; DynamicParameters parameter = new DynamicParameters(); parameter.Add("@Id", user.Id); parameter.Add("@Nickname", user.Nickname); string salt = BCryptHelper.GenerateSalt(); string hashedPassword = BCryptHelper.HashPassword(user.Password, salt); parameter.Add("@Password", hashedPassword); parameter.Add("@StatusId", user.StatusId); parameter.Add("@LastAvailable", user.LastAvailable); parameter.Add("@RegistrationDate", user.RegistrationDate); connection.Query(sqlQuery, parameter); return(true); } return(false); }
public static void Main(string[] args) { // Pasre command line args to config on startup var argConf = new ConfigurationBuilder() .AddCommandLine(args) .Build(); // If config includes 'generateKeyHash', the program will // generate a hash of the passed key based on the passed // parameters and then exit the program with 0 without // actually starting the web server. if (argConf["generateKeyHash"] != null) { var rounds = argConf.GetValue <int>("hashRounds"); rounds = rounds > 0 ? rounds : 12; var salt = BCryptHelper.GenerateSalt(rounds); Console.WriteLine( "Generating Hash of passed keyword...\n\n" + $"Hash Rounds: {rounds}\n" + $"Using Salt: {salt}"); var hash = BCryptHelper.HashPassword(argConf["generateKeyHash"], salt); Console.WriteLine($"Generated Hash: ${hash}"); return; } // Start the web server CreateWebHostBuilder(args).Build().Run(); }
public void Save(IUserSaveDto dto) { _userSaveDtoValidator.Check(dto); if (dto.Id != null) { var user = _dao.Get(dto.Id.Value); user.Name = dto.Name; _dao.Update(user); } else { if (_dao.HasEmail(dto.Email)) { throw new EmailAlreadyExistsException(); } _dao.Create(new User { Name = dto.Name, Email = dto.Email, Password = BCryptHelper.HashPassword(dto.Password, BCryptHelper.GenerateSalt()) }); } }
public string BCrypt1() { string salt = BCryptHelper.GenerateSalt(); string pwd = BCryptHelper.HashPassword("1234567890", salt); return(pwd ?? ""); }
/// <summary> /// Implements <see cref="IPasswordHashing.HashPassword(string)"/> /// </summary> public string HashPassword(string actualPassword) { var salt = BCryptHelper.GenerateSalt(); var hash = BCryptHelper.HashPassword(actualPassword, salt); return(hash); }
public async Task <ActionResult> Register(User model) { var checkEmail = _userRepository.GetByEmail(model.Email); if (checkEmail != null) { return(BadRequest("Email already taken!")); } else { User user = new User(); var mypass = model.Password; var mysalt = BCryptHelper.GenerateSalt(12); user.Email = model.Email; user.Password = BCryptHelper.HashPassword(mypass, mysalt); var result = await _userRepository.PostAsync(user); if (result != null) { await _roleRepository.InsertUserRole(user.Id, 2); return(Ok("Register Success!")); } else { return(BadRequest("Failed to register")); } } }
private BllUser GenerateNewUser(string name, string password) { var user = new BllUser(); user.Name = name; user.PasswordHash = BCryptHelper.HashPassword(password, BCryptHelper.GenerateSalt()); return(user); }