Search code examples
c#.htaccessweb.htpasswd

Create .htpasswd files within C#


For a small tool to automate website deployment I'd like to generate .htaccess and .htpasswd files. How do I create the hashes for the passwords in my code?


Solution

  • Per the documentation on the .htpasswd hashing methods here, the following should produce a suitable line of output that can be inserted into a .htpasswd file, using SHA1 as the hashing algorithm:

    public static string CreateUser(string username, string password)
    {
        using (var sha1 = SHA1.Create())
        {
            var hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(password));
            return string.Format("{0}:{{SHA}}{1}", username, Convert.ToBase64String(hash));
        }
    }
    

    Example:

    Console.WriteLine(CreateUser("TestUser", "TestPassword"));
    

    Will output:

    TestUser:{SHA}YlBiWyJt9ihwriOvjT+sB2DXFYg=

    It should be straightforward to use this method to construct valid .htaccess files.