1

Currently I'm seeking for the possibility for hashing a password in an ActionResult. To be specific, I want to call my SHA512 method in the public ActionResult Edit(User user) to hash the password if it got changed.

Here is the code of the Edit method:

    [HttpPost]
    public ActionResult Edit(User user)
    {
        if (ModelState.IsValid)
        {
            db.Entry(user).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(user);
    }

I am actually new to ASP.NET and I really don't know how to call this method in order to hash the new password, if there is one:

    public static string SHA512(string value)
    {
        byte[] result;
        SHA512 sha512 = new SHA512Managed();
        result = sha512.ComputeHash(Encoding.Default.GetBytes(value));

        string hash = BitConverter.ToString(result).Replace("-", String.Empty); 

        return hash;
    }
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Mehrad Rafigh
  • 156
  • 1
  • 7
  • 20

1 Answers1

0

You update your models by first getting it from database and then calling TryUpdateModel on it. Then you add your new password hash for user (u) that is taken from database and save him.

Side note: Hashing passwords using SHA is very bad because algorithm is fast. Try using PBKDF2 instead.

[HttpPost]
public ActionResult Edit(User user)
{
    var u = db.Users.Single(x => x.Id == user.Id);

    if (TryUpdateModel(u))
    {
        u.Password = SHA512(user.Password)
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(user);
}
Stan
  • 25,744
  • 53
  • 164
  • 242
  • Thank you very much @Steve :) What do you mean by saying Hashing passwords using SHA ist very bad because algorithm is fast? – Mehrad Rafigh Jun 08 '13 at 19:00
  • @user2391883 You can computer hash very fast meaning if someone will steal your hash tables he will brute-force it very fast. Passwords algorithms must be slow so that brute-force attacks are pretty much useless since it takes forever. Also, if someone answers your question you better mark it as answered. – Stan Jun 08 '13 at 19:13
  • @user2391883 In my opinion Steve is not quite right here! SHA512 (even better a salted SHA512) is a really good possibility to secure your passwords. You may have a look at this [question](http://stackoverflow.com/questions/710064/adding-text-to-datagridview-row-header) which calculates 3,17 * 10^64 years necessary to crack a SHA512 hash with brute force. If I understood anything wrong Steve pls let me know! – Pilgerstorfer Franz Jun 08 '13 at 19:21
  • @Steve I'm using the SHA512 Class from Microsoft. Later i will add a Salt to those hash values. I think it should be safe then :) Once again thank you for your answer – Mehrad Rafigh Jun 08 '13 at 19:25