Carlos Saraiva
Carlos Saraiva

Reputation: 21

How should I hash passwords on .NET?

I've made a class that hashes a password to store in the database, and it is a singleton, since I do not want to make an instance of it every time I'm going to use, because it does not change. I've also seen the `PasswordHasher` from Identity Framework, but I'd like to know if the way that I did is a good practice and if the password hash has a secure process and result.

public class Hash
{
    private static Hash _instance = new Hash();

    private Hash() { }

    public static Hash Instance
    {
        get { return _instance; }
    }

    public string HashPasword(string password)
    {
        using (SHA512 hashAlg = SHA512.Create())
        {
            byte[] hash = hashAlg.ComputeHash(Encoding.UTF8.GetBytes(password));
            return BitConverter.ToString(hash).Replace("-", "");
        }
    }

    public bool VerifyPassword(string hashedPassword, string password)
    {
        using (SHA512 hashAlg = SHA512.Create())
        {
            byte[] hashByte = hashAlg.ComputeHash(Encoding.UTF8.GetBytes(password));
            string hash = BitConverter.ToString(hashByte).Replace("-", "");
            if (hash == hashedPassword)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}

This is how I call it.

public async Task<string> CreateUser(
        string email,
        string password,
        [Service] UserRepository userRepository
    )
    {
        string securePassword = Hash.Instance.HashPasword(password);
        if (await userRepository.CreateUser(email, securePassword))
        {
            return "User created successfully!";
        }
        else
        {
            return "User was not created!";
        }
    }

I just want to know if it's good or what should I change if I did something wrong.

Upvotes: 0

Views: 92

Answers (0)

Related Questions