BCrypt.HashPassword()
//Method that registers the user and its debit card public static int RegisterUser(string user, string password, string fName, string lName, decimal amount, OleDbConnection connection) { //Creating GUID for the card unique ID var newGuid = Guid.NewGuid(); //Hasing the password using BCrypt string hashedPwd = BCrypt.HashPassword(password, BCrypt.GenerateSalt()); //Query for inserting the new user in the DB OleDbCommand CommandRegisterUser = new OleDbCommand("INSERT into Users (Username,pass,FirstName,LastName,CardGUID) values (@1,@2,@3,@4,@5)", connection); CommandRegisterUser.Parameters.AddWithValue("@1", user); CommandRegisterUser.Parameters.AddWithValue("@2", hashedPwd); CommandRegisterUser.Parameters.AddWithValue("@3", fName); CommandRegisterUser.Parameters.AddWithValue("@4", lName); CommandRegisterUser.Parameters.AddWithValue("@5", newGuid); CommandRegisterUser.ExecuteNonQuery(); //Used in creating PIN Random rand = new Random(); int pin = rand.Next(1000, 9999); //Query for creating the new Debit card for the newly created user OleDbCommand CommandRegisterCard = new OleDbCommand("INSERT INTO Cards ([GUID],Balance,PIN) VALUES (@guid,@amount,@pin)", connection); CommandRegisterCard.Parameters.AddWithValue("@guid", newGuid); CommandRegisterCard.Parameters.AddWithValue("@amount", amount); CommandRegisterCard.Parameters.AddWithValue("@pin", pin); CommandRegisterCard.ExecuteNonQuery(); return(pin); }
/// <summary> /// Returns account with given name, or null if it doesn't exist. /// </summary> /// <param name="name"></param> /// <returns></returns> public Account GetAccount(string name) { using (var conn = this.GetConnection()) using (var mc = new MySqlCommand("SELECT * FROM `accounts` WHERE `name` = @name", conn)) { mc.Parameters.AddWithValue("@name", name); using (var reader = mc.ExecuteReader()) { if (!reader.Read()) { return(null); } var account = new Account(); account.Id = reader.GetInt64("accountId"); account.Name = reader.GetStringSafe("name"); account.TeamName = reader.GetStringSafe("teamName"); account.Password = reader.GetStringSafe("password"); account.Medals = reader.GetInt32("medals"); account.GiftMedals = reader.GetInt32("giftMedals"); account.PremiumMedals = reader.GetInt32("premiumMedals"); // Upgrade MD5 hashes if (account.Password.Length == 32) { account.Password = BCrypt.HashPassword(account.Password, BCrypt.GenerateSalt()); } return(account); } } }
private bool checkValues() { if (txtOld.Text.Trim() == "" || txtNew.Text.Trim() == "" || txtConfirm.Text.Trim() == "") { MessageBox.Show(this, "Please fill-up the form completely", "Message", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return(false); } if (txtOld.Text.Trim().Length < 5 || txtNew.Text.Trim().Length < 5 || txtConfirm.Text.Trim().Length < 5) { MessageBox.Show(this, "At least 5 characters are needed.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return(false); } if (txtNew.Text.Trim() != txtConfirm.Text.Trim()) { MessageBox.Show(this, "New and confirm passwords do not match.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return(false); } if (BCrypt.CheckPassword(txtOld.Text.Trim() + "33~xX", mPW)) { pw = txtNew.Text.Trim() + vars.staticSalt; salt = BCrypt.GenerateSalt(); hash = BCrypt.HashPassword(pw, salt); this.password = hash; return(true); } else { MessageBox.Show(this, "Old Password is invalid.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return(false); } }
public void HashPassword_DefaultSalt_GeneratesSaltedPassword() { string password = "******"; string hashed = BCrypt.HashPassword(password, BCrypt.GenerateSalt()); Assert.That(hashed, Is.Not.EqualTo(password)); }
public void CheckPassword_AnotherSaltedPassword_False() { string password = "******"; string hashed = BCrypt.HashPassword("anotherPassword", BCrypt.GenerateSalt(6)); Assert.That(BCrypt.CheckPassword(password, hashed), Is.False); }
public static string GenerateBCryptHash(string _input) { //adjust salt level here below" string salt = BCrypt.GenerateSalt(); return(BCrypt.HashPassword(AntiXSSMethods.CleanString(_input), salt)); }
public void LeadingByteDoesntTruncateHash() { var b = new BCrypt(); var s = BCrypt.GenerateSalt(); var extractedSalt = s.Substring(7, 22); var passA = SafeUTF8.GetBytes("\0 password"); var passB = SafeUTF8.GetBytes("\0"); byte[] saltBytes = BCrypt.DecodeBase64(extractedSalt, 128 / 8); var bytesAreValid = BytesAreValid(passA); Assert.False(bytesAreValid, "Hash contains null bytes"); var hashA = b.CryptRaw(passA, saltBytes, 4); var hashAVerification = b.CryptRaw(passA, saltBytes, 4); Assert.True(Convert.ToBase64String(hashA) == Convert.ToBase64String(hashAVerification), "These should match as this is how validation works"); var hashB = b.CryptRaw(passB, saltBytes, 4); var hashBVerification = b.CryptRaw(passB, saltBytes, 4); Assert.True(Convert.ToBase64String(hashB) == Convert.ToBase64String(hashBVerification), "These should match as this is how validation works, this is skipping the password"); Assert.False(Convert.ToBase64String(hashA) == Convert.ToBase64String(hashB), "These shouldnt match as we hash the whole strings bytes, including the null byte"); }
/// <summary> /// Creates new account with given information. /// </summary> /// <param name="name"></param> /// <param name="password"></param> /// <returns></returns> /// <exception cref="ArgumentNullException">Thrown if name or password is empty.</exception> public bool CreateAccount(string name, string password) { if (string.IsNullOrWhiteSpace(name)) { throw new ArgumentNullException("name"); } if (string.IsNullOrWhiteSpace(password)) { throw new ArgumentNullException("password"); } // Wrap password in BCrypt password = BCrypt.HashPassword(password, BCrypt.GenerateSalt()); using (var conn = this.GetConnection()) using (var cmd = new InsertCommand("INSERT INTO `accounts` {0}", conn)) { cmd.Set("name", name); cmd.Set("password", password); try { cmd.Execute(); return(true); } catch (Exception ex) { Log.Exception(ex, "Failed to create account '{0}'.", name); } } return(false); }
private void ChangingPassword() { try { string passwordPlain = txtConfirmNewPassword.Text; string passwordHash = BCrypt.HashPassword(passwordPlain, BCrypt.GenerateSalt(12)); Objects.con.Open(); Objects.cmd = new SqlCommand("UPDATE tbl_students SET password=@password WHERE id=@id", Objects.con); Objects.cmd.CommandType = System.Data.CommandType.Text; Objects.cmd.Parameters.Add(new SqlParameter("@password", passwordHash)); Objects.cmd.Parameters.Add(new SqlParameter("@id", studentId)); Objects.cmd.ExecuteNonQuery(); Objects.con.Close(); Objects.cmd.Dispose(); pnlWarning.Visible = false; Page.ClientScript.RegisterStartupScript(this.GetType(), "Scripts", "<script>alert('Successfully set a new password for your account!'); </script>"); Response.Redirect("../students/Default.aspx"); } catch (Exception ex) { txtNewPassword.Focus(); pnlWarning.Visible = true; lblWarning.Text = "Please contact your programmer. Because this program now has an error called " + ex.Message + Environment.NewLine + ex.StackTrace; } }
private string HashPassword(string password) { string salt = BCrypt.GenerateSalt(); string hash = BCrypt.HashPassword(password, salt); return(hash); }
public async Task <User> CreateUser(User user, string password) { if (!(await _userTable.SelectByUsername(user.Username)).Any()) // Check if username already exists { string hashedPassword = BCrypt.HashPassword(password, BCrypt.GenerateSalt()); // Hash password await _userTable.Insert(user, hashedPassword); // Insert user into database user = await GetUserByUsername(user.Username); foreach (Role role in user.Roles) { if ((await _roleTable.SelectById(role.Id)).Any()) // Check if role exists { await _userRoleTable.Insert(new UserRoleModel { UserId = user.Id, RoleId = role.Id }); // Insert new user role relation } else { throw new ArgumentException("Provided role does not exist."); // TODO: Could fail gracefully and simply not add role } } return(await GetUserById(user.Id)); } else { throw new ArgumentException("Provided username is already in use."); } }
private void UpdateExistingStudent() { try { int studentId = Convert.ToInt32(Request.QueryString["studentId"]); string passwordPlain, passwordHash; if (txtPassword.Text != "") { passwordPlain = txtPassword.Text; passwordHash = BCrypt.HashPassword(passwordPlain, BCrypt.GenerateSalt(12)); } else { passwordHash = ""; } string secretAnswerPlain, secretAnswerHash; if (txtSecretAnswer.Text != "") { secretAnswerPlain = txtSecretAnswer.Text; secretAnswerHash = BCrypt.HashPassword(secretAnswerPlain, BCrypt.GenerateSalt(12)); } else { secretAnswerHash = ""; } Admin.RetrieveAdminId(Session["AdminEmail"].ToString()); int adminIdValue = Admin.adminId; Objects.con.Open(); Objects.cmd = new SqlCommand("sp_UpdateExistingStudent", Objects.con); Objects.cmd.CommandType = CommandType.StoredProcedure; Objects.cmd.Parameters.AddWithValue("@password", passwordHash); Objects.cmd.Parameters.AddWithValue("@full_name", txtFullName.Text); Objects.cmd.Parameters.AddWithValue("@secret_question", ddlSecretQuestion.Text); Objects.cmd.Parameters.AddWithValue("@secret_answer", secretAnswerHash); Objects.cmd.Parameters.AddWithValue("@registered_date_time", DateTime.Now); Objects.cmd.Parameters.AddWithValue("@admin_id", adminIdValue); Objects.cmd.Parameters.AddWithValue("@account_or_exam_status_id", ddlAccountStatus.SelectedValue); Objects.cmd.Parameters.AddWithValue("@id", studentId); int i = Objects.cmd.ExecuteNonQuery(); if (i > 0) { Objects.con.Close(); Objects.cmd.Dispose(); pnlEditStudentWarning.Visible = false; Response.Redirect("~/admin/Form_Students.aspx"); } else { Objects.con.Close(); Objects.cmd.Dispose(); pnlEditStudentWarning.Visible = true; lblEditStudentWarning.Text = "Something went wrong. Can't update. Please try after sometime later</br> "; } } catch (Exception ex) { pnlEditStudentWarning.Visible = true; lblEditStudentWarning.Text = "Please contact your programmer. Because this program now has an error called " + ex.Message + Environment.NewLine + ex.StackTrace; } }
public void LeadingByteDoesntTruncateHashSHA() { var b = new BCrypt(); var s = BCrypt.GenerateSalt(); var extractedSalt = s.Substring(7, 22); var passA = SafeUTF8.GetBytes("d27a37"); var passB = new byte[] { 0 }; byte[] saltBytes = BCrypt.DecodeBase64(extractedSalt, 128 / 8); byte[] enhancedBytes = SHA384.Create().ComputeHash(passA); byte[] enhancedBytesB = SHA384.Create().ComputeHash(passB); var bytesAreValid = BytesAreValid(enhancedBytes); Assert.False(bytesAreValid, "Hash contains null bytes"); var hashA = b.CryptRaw(enhancedBytes, saltBytes, 4); var hashAVerification = b.CryptRaw(enhancedBytes, saltBytes, 4); Assert.True(Convert.ToBase64String(hashA) == Convert.ToBase64String(hashAVerification), "These should match as this is how validation works"); var hashB = b.CryptRaw(enhancedBytesB, saltBytes, 4); var hashBVerification = b.CryptRaw(enhancedBytesB, saltBytes, 4); Assert.True(Convert.ToBase64String(hashB) == Convert.ToBase64String(hashBVerification), "These should match as this is how validation works"); Assert.False(Convert.ToBase64String(hashA) == Convert.ToBase64String(hashB), "These shouldnt match as we hash the whole strings bytes, including the null byte"); }
/* public List<TECNOLOGIA> GetTecnologiasPorEstudiante(string idEstudiante) * { * return db.TECNOLOGIA.Where(tecno => idiom.IdEstudiante != idEstudiante).ToList<VIEW_IDIOMA_POR_ESTUDIANTE>(); * }*/ /// <summary> /// /// </summary> /// <param name="estudiante"></param> /// <returns></returns> public bool doStudentInsertion(VIEW_ESTUDIANTE estudiante) { clsIncrementalIdGenerator lobj_generator = new clsIncrementalIdGenerator(); //genera un id autoincremental estudiante.Id = lobj_generator.generateUserId(); //generar sal estudiante.Sal = BCrypt.GenerateSalt(); //encriptar la constraseña estudiante.Contrasena = BCrypt.HashPassword(estudiante.Contrasena, estudiante.Sal); db.SP_Insertar_Estudiante(estudiante.Id, estudiante.Contrasena, estudiante.Sal, estudiante.RepositorioArchivos, estudiante.CredencialDrive, estudiante.NombreContacto, estudiante.ApellidoContacto, estudiante.Carne, estudiante.Email, estudiante.Telefono, estudiante.Pais, estudiante.Region, estudiante.IdUniversidad, estudiante.RepositorioCodigo, estudiante.LinkHojaDeVida, estudiante.NombreDeUsuario); try { db.SaveChanges(); } catch (DbUpdateException) { if (ESTUDIANTEExists(estudiante.Id)) { return(false); } else { throw; } } return(true); }
public ActionResult Add(HernaUser hernaUser) { if (ModelState.IsValid) { HernaRoleDao hernaRoleDao = new HernaRoleDao(); HernaRole role = hernaRoleDao.GetById(2); hernaUser.Role = role; string hasher = BCrypt.HashPassword(hernaUser.Password, BCrypt.GenerateSalt(12)); hernaUser.Password = hasher; HernaUserDao hernaUserDao = new HernaUserDao(); if (hernaUserDao.GetByLogin(hernaUser.Login) == null) { hernaUserDao.Create(hernaUser); TempData["message-success"] = "Registrace proběhla úspěšně, nyní se můžete přihlásit"; } else { TempData["error"] = "Uživatel s tímto uživatelským jmenem již existuje"; return(View("Registrace", hernaUser)); } } else { TempData["error"] = "Nějaká pole nejsou správně vyplněna"; return(View("Registrace", hernaUser)); } return(RedirectToAction("Index", "Login")); }
protected void btnchgpwd_Click(object sender, EventArgs e) { lblErrorMesage.Text = ""; if (txtpassword1.Text.ToString().Trim() == txtpassword2.Text.ToString().Trim()) { decimal alias = Convert.ToDecimal(HttpContext.Current.Session["UserID"].ToString().Trim().Substring(0, 4)); string sltforpwd = BCrypt.GenerateSalt(10); string hashedpassword = BCrypt.HashPassword(txtpassword1.Text.ToString().Trim(), sltforpwd); decimal userid = Convert.ToDecimal(Session["UserID"].ToString().Trim()); try { VPCRMSBAL.UdpateUserPassword(alias, userid, hashedpassword); lblErrorMesage.Text = "Success. You will be redirected to Login."; Response.Redirect("Login.aspx"); } catch { } } }
/// <summary> /// Generates the password salt. /// </summary> /// <param name="user">The user.</param> /// <param name="userPassword">The user password.</param> /// <returns></returns> public Task <string> GeneratePasswordSalt(string user, string userPassword) { #region CheckParameters if (String.IsNullOrEmpty(user)) { throw new ArgumentException("Username cannot be null or empty.", "username"); } if (String.IsNullOrEmpty(userPassword)) { throw new ArgumentException("Password cannot be null or empty.", "password"); } #endregion string pwdToHash = userPassword + "$2a$&sdjkj#s"; string hashToStoreInDatabase = BCrypt.HashPassword(pwdToHash, BCrypt.GenerateSalt()); TaskCompletionSource <string> tks = new TaskCompletionSource <string> (); if (!String.IsNullOrEmpty(hashToStoreInDatabase)) { tks.SetResult(hashToStoreInDatabase); } return(tks.Task); }
/// <summary> /// Create a new account /// </summary> /// <param name="username">username</param> /// <param name="email">email address</param> /// <param name="password">password</param> /// <returns></returns> public static bool CreateAccount(string username, string email, string password) { // Connect to the MSSQL database using (MSSqlConnection connection = MSSqlConnection.GetConnection()) { // Get the table Table <AccountTable> accounts = connection.GetTable <AccountTable>(); // Check if the username and e-mail address are free if (accounts.Any(x => x.Username.ToLower() == username.ToLower())) { return(false); } if (accounts.Any(x => x.EmailAddress.ToLower() == email.ToLower())) { return(false); } // Insert the new user accounts.InsertOnSubmit(new AccountTable() { Username = username.ToLower(), EmailAddress = email.ToLower(), Password = BCrypt.HashPassword(password, BCrypt.GenerateSalt()), Enabled = true, Role = (int)AccountRole.Editor, }); // Submit the changes connection.SubmitChanges(); // Success return(true); } }
public ActionResult Register(RegisterModel registerModel) { if (!ModelState.IsValid) { return(View()); } var bcryptHashed = BCrypt.HashPassword(registerModel.Password, BCrypt.GenerateSalt(10)); var createStatus = AccountService.CreateUser( registerModel.Username, bcryptHashed, registerModel.Email ); if (createStatus == AccountService.AccountCreateStatus.Success) { // AuthenticationService.SignIn(registerModel.Username, false /* createPersistentCookie */); // return RedirectToAction("Login", "Account", new { registered = "true" }); return(RedirectToAction("login", "account", new { message = "registersuccess" })); } else { ViewBag.Notification = string.Format("showError('{0}');", AccountValidation.ErrorCodeToString(createStatus)); ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus)); } return(View(registerModel)); }
public void CheckPassword_SameSaltedPassword_True() { string password = "******"; string hashed = BCrypt.HashPassword(password, BCrypt.GenerateSalt(6)); Assert.That(BCrypt.CheckPassword(password, hashed), Is.True); }
public string GetSalt() { if (Salt == "" || Salt == null) { Salt = BCrypt.GenerateSalt(); } return(Salt); }
private string SetPassword(string userPassword) { string pwdToHash = userPassword; string mySalt = BCrypt.GenerateSalt(); string hashToStoreInDatabase = BCrypt.HashPassword(pwdToHash, mySalt); return(hashToStoreInDatabase); }
public long Post([FromBody] Admin value) { string pwdToHash = value.Password + "$O*#La"; string hashToStoreInDatabase = BCrypt.HashPassword(pwdToHash, BCrypt.GenerateSalt()); value.Password = hashToStoreInDatabase; return(GetDatastore().Create(value)); }
public void HashPassword_SaltMatters() { string password = "******"; string hashedDefault = BCrypt.HashPassword(password, BCrypt.GenerateSalt()), hashedSix = BCrypt.HashPassword(password, BCrypt.GenerateSalt(6)); Assert.That(hashedDefault, Is.Not.EqualTo(hashedSix)); }
public string getCryptPassword(string password) { string hashPasword = password + CryptKey.PetterSalt; string petterSalt = BCrypt.GenerateSalt(); string hashCode = BCrypt.HashPassword(hashPasword, petterSalt); return(hashCode); }
protected void btnEditar_Click(object sender, EventArgs e) { try { Usuario usuario = new Modelo.Usuario(); Modelo.Cliente cliente = SesionCl; if (MiSesion.TIPO_USUARIO.Equals(Tipo_Usuario.Cliente.ToString()) && MiSesion.ESTADO.Equals(Estado_Usuario.Habilitado.ToString())) { usuario = MiSesion; } else { usuario = SesionEdit; } if (!string.IsNullOrEmpty(txtPassword.Text) && !string.IsNullOrEmpty(txtConfirmar.Text) && txtPassword.Text.Equals(txtConfirmar.Text)) { string hashed = BCrypt.HashPassword(txtPassword.Text, BCrypt.GenerateSalt(12)); usuario.PASSWORD = hashed; } if (!txtNombreC.Text.Equals(cliente.NOMBRE_CLIENTE)) { cliente.NOMBRE_CLIENTE = txtNombreC.Text; } if (!txtDireccion.Text.Equals(cliente.DIRECCION_CLIENTE)) { cliente.DIRECCION_CLIENTE = txtDireccion.Text; cliente.ID_COMUNA = short.Parse(ddlComuna.SelectedValue); } if (!txtEmail.Text.Equals(cliente.CORREO_CLIENTE)) { cliente.CORREO_CLIENTE = txtEmail.Text; } if (!txtTelefono.Text.Equals(cliente.TELEFONO_CLIENTE.ToString())) { cliente.TELEFONO_CLIENTE = long.Parse(txtTelefono.Text); } if (usuario.Update() && cliente.Update()) { if (MiSesion.TIPO_USUARIO.Equals(Tipo_Usuario.Cliente.ToString()) && MiSesion.ESTADO.Equals(Estado_Usuario.Habilitado.ToString())) { Response.Write("<script language='javascript'>window.alert('Se ha actualizado con éxito.');window.location='../Cliente/WebCliente.aspx';</script>"); } else { Response.Write("<script language='javascript'>window.alert('Se ha actualizado con éxito.');window.location='../Administrador/WebVerUsuarios.aspx';</script>"); } } else { error.Text = "La actualización ha fallado"; alerta.Visible = true; } } catch (Exception) { error.Text = "Excepcion"; alerta.Visible = true; } }
public void Test_Encription() { string Sal = BCrypt.GenerateSalt(); string myPassword = "******"; string myHash = BCrypt.HashPassword(myPassword, Sal); Assert.AreNotEqual(myPassword, myHash); Assert.AreEqual(myHash, BCrypt.HashPassword(myPassword, Sal)); }
public void NullTerminationCausesBCryptToTerminateStringInSomeFrameworks(bool enhanced) { string password = "******"; // can cause zero bytes long (an empty password) for bcrypt passphrase. string hash = BCrypt.HashPassword(password, BCrypt.GenerateSalt(), enhanced); var t1 = BCrypt.Verify(password, hash, enhanced); var t2 = BCrypt.Verify("\0", hash, enhanced); Assert.True(t1, "Null terminator should validate if part of passphrase"); Assert.False(t2, "Null terminator shouldnt alter passphrase"); }
public void Test_CheckPassword() { string Sal = BCrypt.GenerateSalt(); string myPassword = "******"; string wrongPassword = "******"; string myHash = BCrypt.HashPassword(myPassword, Sal); Assert.AreEqual(true, BCrypt.CheckPassword(myPassword, myHash)); Assert.AreEqual(false, BCrypt.CheckPassword(wrongPassword, myHash)); }
public void NullTerminationCausesBCryptToTerminateStringInSomeFrameworks(bool enhanced, string password) { var x = BCrypt.GenerateSalt(); string hash = BCrypt.HashPassword(password, x, enhanced); var t1 = BCrypt.Verify(password, hash, enhanced); var t2 = BCrypt.Verify("password", hash, enhanced); Assert.True(t1, "Null terminator should validate if part of passphrase"); Assert.False(t2, "Null terminator shouldnt alter passphrase"); }