Create htpasswd bcrypt hashes in .NET

BCrypt.Net-Next is the maintained bcrypt package for .NET. Generate the salt with revision y to get the $2y$ prefix.

Install

dotnet add package BCrypt.Net-Next

Create a line

using BCryptNet = BCrypt.Net.BCrypt;

static string HtpasswdLine(string user, string password, int cost = 10)
{
    if (user.Length == 0 || user.Contains(':'))
        throw new ArgumentException("User name must be non-empty and contain no colon.");
    var salt = BCryptNet.GenerateSalt(cost, 'y');
    return $"{user}:{BCryptNet.HashPassword(password, salt)}";
}

File.AppendAllText("/etc/nginx/.htpasswd", HtpasswdLine("admin", "correct horse") + "\n");

Check a password

var parts = line.Trim().Split(':', 2);
bool ok = BCryptNet.Verify(password, parts[1]);

Notes

  • Verify accepts $2a$, $2b$, $2x$ and $2y$ hashes.
  • Do not use the EnhancedHashPassword methods for htpasswd: they pre-hash with SHA-384 and Apache and Nginx cannot verify the result.

Related tool: htpasswd generator. Runs in your browser; input is not uploaded.

More on this tool