FormsAuthentication HashPasswordForStoringInConfigFile in Windows.Forms


Lord Jesus in the heaven! I refuse to reference System.Web in my Windows.Forms application… period! So i went to look for an alternative to HashPasswordForStoringInConfigFile. You need this if for example:

– in your win forms client you want to use same DB you are using in your web application;
– you use secure web-services which should authenticate user of your win forms client against her identity in DB of your web application;

Pretty much common scenarios, ey? I’ve still got sweaty armpits and bleeding nose from all the crunching through bazillions of forums and blogs. With no success.

Now, after two hours of putting bits and bytes together here’s WORKING version of the method in c# that will generate identical hash with that of HashPasswordForStoringInConfigFile from plain password stored in string:

string EncryptPassword(string password)
{
  Byte[] passwordBytes = (new ASCIIEncoding()).GetBytes(password);
  SHA1Managed hashProvider = new SHA1Managed();
  hashProvider.Initialize();
  passwordBytes = hashProvider.ComputeHash(passwordBytes);
  hashProvider.Clear();
  string encryptedPassword = string.Empty;

  foreach (byte b in passwordBytes)
  {
    encryptedPassword += b.ToString("X2");
  }

  return encryptedPassword;
}

Don’t get fooled by simplicity of this method, because it wasn’t simple at all to make it work. Here are pitfalls I falled into:

– (new ASCIIEncoding()).GetBytes(password); <- do NOT use unicode encoding here no matter that your password contains unicode characters cause that’s how FormsAuthentication method does it;
– encryptedPassword += b.ToString(“X2”); <- forget “2” in that format string and resulting hash will be ALMOST identical but not EXACTLY since FormsAuthentication generates with leading zero!
– no, the loop does not the same thing Convert.ToBase64String does, don’t even ask!


2 responses to “FormsAuthentication HashPasswordForStoringInConfigFile in Windows.Forms”

  1. Thanks a lot, the conversion to string was throwing me, this is what I was looking for to replace HashPasswordForStoringInConfigFile