Encrypt password with C#

I borrowed the code for this post from:

And before reading further, make sure you understand the concepts of hashing and generating salts to secure a password. This article provides a good overview:

https://auth0.com/blog/hashing-passwords-one-way-road-to-security/

So based on the above links I have added three static functions to a UserModel class: GenerateSalt(), HashPassword() and VerifyPassword().

The GenerateSalt function generates a random salt which is used to improve the security of the hashed password.

private static string GenerateSalt()
{
	var bytes = new byte[128 / 8];
	var rng = new RNGCryptoServiceProvider();
	rng.GetBytes(bytes);

	return Convert.ToBase64String(bytes);                
}

The HashPassword function takes a password and salt and returns a string consisting of the hashed password and the salt joined with a full stop (.).

public static string HashPassword(string password, string salt = null)
{
	// Generate the Salt
	var genSalt = (salt == null) ? GenerateSalt() : salt;

	// Hash the password
	var byteResult = new Rfc2898DeriveBytes(Encoding.UTF8.GetBytes(password), Encoding.UTF8.GetBytes(genSalt), 10000);
	var hash = Convert.ToBase64String(byteResult.GetBytes(24));

	return hash + "." + salt;
}

The result of the HashPassword function can be stored in the database and when a user logs in what I will do is load the result and compare it to the provided user password using the VerifyPassword function.

public static bool VerifyPassword(string password, string digest)
{
	// Split the digest into two parts
	var parts = digest.Split(".");
	var storedHash = parts[0];
	var storedSalt = parts[1];

	var hash = HashPassword(password, storedSalt);

	return (hash == storedHash);
}

And this provides the building blocks for a user authentication system written in C#. I am using .NET Core 5.0 and will explain how I will expose these functions in a Web Api in future posts.

Leave a comment

Your email address will not be published. Required fields are marked *