Generating Apache compatible .htpasswd users in C#


I've been working on my web server component for a while now and I've recently arrived at the point where I would like to start implementing user authentication. I've decided to go the route of Apache's .htpasswd files, this way configuration and directory trees created for my web server component can be moved over to Apache with ease.

I'm using the Microsoft .NET 2.0 Framework and would like to stay within it as much as possible without having to write excessively long classes or use third party assemblies.

It seems that htpasswd codes the username and password using three functions:

Unix crypt() - I've been able to locate a few functions on the web which emulate the Unix cypt() function within C#. One is this function coded by Jeroen-bart Engelen which is actually a port of a function originally written using Java by John Dumas (located here). This is a fairly bulky class to be adding to my rather small application and only works with *nix based versions of Apache.

MD5 - The MD5 flag used in htpasswd is specific to only Apache, as it uses a "modified MD5 algorithm". This means the MD5 class within System.Cryptography won't generate a matching MD5 by using it's GetHash() method.

SHA1 - I seemed to have struck gold on this one, as SHA1 is the same across the board, no matter which platform. Apache supports SHA1 hash's in .htpasswd files and the SHA class within System.Cryptography generates matching hashes using the GetHash() method.

Apache can identify SHA1 hashed passwords because they're prefaced by the string {SHA}. An example of a user entry hashed using SHA would be:

eric:{SHA}W6ph5Mm5Pz8GgiULbPgzG37mj9g=

Below is the code needed to create compatible user entries for .htpasswd files in Apache using C#:

C#:
  1. public string Convert_PlaintextAuthToSHAAuth(string sAuth)
  2. {
  3. string[] sPassword = sAuth.Split(new char[] { ':' })//Extract the password
  4.  
  5. return  sPassword[0] + ":{SHA}" + Convert.ToBase64String(Create_SHA1Hash(Encoding.ASCII.GetBytes(sPassword[1])));
  6. }
  7.  
  8. public byte[] Create_SHA1Hash(byte[] byInput)
  9. {
  10. SHA1 sha1 = new SHA1CryptoServiceProvider();
  11. return sha1.ComputeHash(byInput);
  12. }

The function Convert_PlaintextAuthToSHAAuth() accepts an input of an unencoded user login as "username:password".

Example Input: eric:password

Example Output: eric:{SHA}W6ph5Mm5Pz8GgiULbPgzG37mj9g=

Using the function above, you can create user strings that will be compatible with Apache in it's .htpasswd files!

Enjoy!

  1. #1 by Hannes on July 28, 2010 - 9:58 AM

    Great snippet, it works well with apache. Do you know if other webservers support SHA encryption as .htaccess password?

(will not be published)

Powered by WP Hashcash