title: Asp.net MVC - How to hash password
body: <p>How do I hash an users input(password) to database and then later read the hashed password during login? </p>
  
  <p>I believe the solution is to hash the password upon register, where the password is saved as hashed inside db. Later upon Login, it should un-hash and compare its password with users password-input. 
  But I don't know how to do it. </p>
  
  <p>I allowed password to have <code>nvarchar(MAX)</code>in db since hashed password are usually long.</p>
  
  <pre><code>        [Required]
          [StringLength(MAX, MinimumLength = 3, ErrorMessage = "min 3, max 50 letters")]
          public string Password { get; set; }
  </code></pre>
  
  <p>Register:</p>
  
  <pre><code>        [HttpPost]
          public ActionResult Register(User user) {
              if (ModelState.IsValid) {
  
                          var u = new User {
                              UserName = user.UserName,                               
                              Password = user.Password
                          };
  
                          db.Users.Add(u);
                          db.SaveChanges();
  
                      return RedirectToAction("Login");
                  }
              }return View();    
          }
  </code></pre>
  
  <p>Login: </p>
  
  <pre><code>  public ActionResult Login() {
          return View();
      }
  
      [HttpPost]
      [ValidateAntiForgeryToken]
      public ActionResult Login(User u) {
          if (ModelState.IsValid) 
          {
              using (UserEntities db = new UserEntities()) {
  
                  //un-hash password?
  
                  var v = db.Users.Where(a =&gt; a.UserName.Equals(u.UserName) &amp;&amp; a.Password.Equals(u.Password)).FirstOrDefault();
                  if (v != null) {
  
                      return RedirectToAction("Index", "Home"); //after login
                  }
              }
          }return View(u);
      }
  </code></pre>
  
  <p>I'm using database first.</p>