How to implement password encryption?

Asked

Viewed 230 times

0

I want to implement password encryption in user registration. I found here in stackoverflow this post teaching how to use cryptography, but I’m in doubt where to add the code.

This method should be used in the class or controller?

public string CalculateMD5Hash(string input)
{
    // Calcular o Hash
    MD5 md5 = System.Security.Cryptography.MD5.Create();
    byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
    byte[] hash = md5.ComputeHash(inputBytes);

    // Converter byte array para string hexadecimal
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < hash.Length; i++)
    {
        sb.Append(hash[i].ToString("X2"));
    }
    return sb.ToString();
}

To use, where should I call?

seuModel.Senha = EncodePassword(senha);

People Controller, where register the user:

public ActionResult Create()
{
    return View();
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Nome,Email,Senha")] Pessoas pessoas)
{
    if (ModelState.IsValid)
    {
        db.Pessoas.Add(pessoas);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(pessoas);
}

In the user registration view I have the password field, so:

<div class="form-group col-sm-6">
    @Html.LabelFor(model => model.Senha, htmlAttributes: new { @class = "control-label" })
    @Html.EditorFor(model => model.Senha, new { htmlAttributes = new { @class = "form-control" } })                
    @Html.ValidationMessageFor(model => model.Senha, "", new { @class = "text-danger" })
</div>
  • 3

    Do not mix the responsibilities. The password should already go ciptografada for your model make only the recording in the bank, that is, this method would be called in your controller.

  • 2

    A suggestion would be to use Identity for your login system, it implements several security tools, if you have at the beginning of your project is very worth using

1 answer

3


Good afternoon.

Use this method before carrying out the persistence of that model in the bank.

For example:

public void SalvarUsuario(Usuario model){
    using (var db = new objetoConexaoBanco()){
        model.Senha = CalculateMD5Hash(model.Senha);
        db.Usuario.Add(model);
        db.SaveChanges();
    }
}

This example is using Entity Framework.

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Nome,Email,Senha")] Pessoas pessoas)
{
    if (ModelState.IsValid)
    {
        pessoas.Senha = CalculateMD5Hash(pessoas.Senha);
        db.Pessoas.Add(pessoas);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(pessoas);
}

The example above is how your code would be.

  • I tried to use this method inside Create’s if (Modelstate.Isvalid) [Httppost], but it gave error in the Calculatemd5hash(model model)

  • If you are actually using the same function, then you could not pass model and yes model password, for example model.Senha = CalculateMD5Hash(model.Senha)

  • Please take a look again at the answer as I made a change to it.

  • Error "Exception User-Unhandled" in "db.Savechanges();"

  • 1

    To check this error you should see the Exception that is being returned, sometimes it may be the size that is trying to be populated the field, I may be mistaken, but the MD5 hash size is 32 characters, so you should take a look at the size of the Password column in the database, otherwise you should look at Exception, either in Message or in Innerexception to verify what was the original error.

  • That’s right, my bank was a varchar(16). Thanks for the solution and help.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.