Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Don't use SHA256 to hash your passwords! Hash passwords the correct way, using BCrypt.
/// <summary>
/// Requires the BCrypt nuget package. Available here: https://www.nuget.org/packages/BCrypt.Net-Next
/// </summary>
public static class PasswordHashing
{
public static string HashPassword(string password, int workFactor)
{
return BCrypt.Net.BCrypt.HashPassword(password, workFactor);
}
public static bool ValidatePassword(string password, string hashedString)
{
return BCrypt.Net.BCrypt.Verify(password, hashedString);
}
/// <summary>
/// Returns the work factor number thats closest to the specified target time.
/// </summary>
public static int FindTargetWorkFactor(long targetTimeInMilliseconds)
{
int currentWorkFactor = 10;
int maximumWorkFactor = 31;
long timeTarget = targetTimeInMilliseconds;
long timeTaken = 0;
long lastTime = 0;
do
{
lastTime = timeTaken;
currentWorkFactor += 1;
Stopwatch timer = Stopwatch.StartNew();
BCrypt.Net.BCrypt.HashPassword("RwiKnN>9xg3*C)1AZl.)y8f_:GCz,vt3T]PI", currentWorkFactor);
timer.Stop();
timeTaken = timer.ElapsedMilliseconds;
Console.WriteLine($"A work-factor of {currentWorkFactor} took {timeTaken.ToString().PadLeft(4, ' ')} milliseconds.");
}
while (timeTaken < timeTarget && currentWorkFactor < maximumWorkFactor);
long timeDiff_Last = Math.Abs(targetTimeInMilliseconds - lastTime);
long timeDiff_Current = Math.Abs(timeTaken - targetTimeInMilliseconds);
if (timeDiff_Last < timeDiff_Current)
{
return currentWorkFactor - 1;
}
return currentWorkFactor;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment