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?
Asked
Active
Viewed 1,909 times
0
-
Can you not use the existing "small tool" (htpasswd) that comes with Apache? – Iridium Feb 04 '13 at 20:28
-
@Iridium: I tried this, thank you for the hint. It was a little bit uncomfortable. I used your approach with the SHA1 hash. – ldrdl Feb 05 '13 at 09:52
1 Answers
6
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.

Iridium
- 23,323
- 6
- 52
- 74