How to implement encryption in the password?

0

I want to implement password encryption in the user registry. I found here on stackoverflow this post teaching how to use encryption, but I'm in doubt where I should add the code.

Should this method 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);

Controller People, where you 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 account view I have the password field, like this:

<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>
    
asked by anonymous 22.10.2018 / 18:24

1 answer

2

Good afternoon.

Use this method before performing the persistence of this template in the database.

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 the 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 above example is what your code looks like.

    
22.10.2018 / 20:01