Search code examples
c#asp.net-mvcmodel

Datatype Model validation for Password


What is the role of [DataType(DataType.Password)] in model? When I'm applying this in my model this will not convert my password into hash format and all passwords are in readable form.


Solution

  • Maybe you can find about dataType here EmailAddress or DataType.Email attribute

    If you want to convert password into hash, you can use SHA256.

    This method returns hash, you need to pass password as parameter:

    public static string Sha256Hash(string value, string salt = default)
            {
                using var sha256Hash = SHA256.Create();
                {
                    var hash = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(value + salt));
    
                    var builder = new StringBuilder();
                    
                    for (var i = 0; i < hash.Length; i++)
                    {
                        builder.Append(hash[i].ToString("x2"));
                    }
    
                    return builder.ToString();
                }
            }