0

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.

3
  • 1
    Security Best Practices: 1) do not roll your own. 2) password hashes should be salted. Anyway, this has some updated answers for 2022: stackoverflow.com/questions/2138429/… Commented Jan 15, 2024 at 14:13
  • 2
    Does this answer your question? Hash and salt passwords in C# Commented Jan 15, 2024 at 14:20
  • 2
    Additionally, your approach applies a fast digest, which is also a vulnerability. Usually dedicated functions like Argon2 or at least PBKDF2 are used to slow down attackers. There are many posts on this, e.g. here. Commented Jan 15, 2024 at 14:21

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.