views:

170

answers:

5

I have written a quick console app to quickly go and generate usernames and logins for my web application for existing accounts that did not have properly hashed passwords. In my web application I am using FormsAuthentication like so:

string hashedPwd = FormsAuthentication.HashPasswordForStoringInConfigFile(saltAndPassword, "SHA1");

I tried to use FormsAuthentication in the console app but it cannot resolve the FormsAuthentication nor the imports. The warning I get asks if I am missing an assembly. I tried to use the following to give me the same results as the previous:

SHA1 sha1 = new SHA1CryptoServiceProvider();
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
byte[] bytesHashedPwd = sha1.ComputeHash(encoding.GetBytes(saltAndPwd));
string tmpString =  encoding.GetString(byteshashedPwd);
string hashedPwd = String.Concat(str, salt);
return hashedPwd;

These two methods are giving me different results. I need to get the same result as FormsAuthentication. I am no security expert with a tiny vauge background and my character set knowledge is even worse. I apprecaite any help.

+3  A: 

Here is a good explanation of how to match the format. Hope it helps.

http://www.stardeveloper.com/articles/display.html?article=2003062001&page=1

I believe the difference is the forms authentication hashes it to a hexadecimal string.

apocalypse9
I needed to add ConvertToBase64String.
uriDium
+2  A: 

If you're curious, the code used by that method is:

return MachineKeySection.ByteArrayToHexString(
    SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(password)),
    0
);
John Rasch
+3  A: 

It seems to work for me.

  • I added a reference to System.Web
  • I added using System.Web.Security

Then I used your code snippet:

string hashedPwd = FormsAuthentication.HashPasswordForStoringInConfigFile(saltAndPassword, "SHA1");

To get the result. This was in a console application.

Tuzo
I am such an idiot. I am new to .Net. Adding the refernce solved it too. Both of you helped me. Sorry I picked apoc's answer first though.
uriDium
A: 

I was able to add the System.Web reference to a console app and use

string hashedPwd = FormsAuthentication.HashPasswordForStoringInConfigFile(saltAndPassword, "SHA1");
Pharabus
A: 

Here's another solution to avoid the System.Web.dll dependency, in C#:

public static string SHA1(this string stringToHash)
{
    // SHA1 is 160bit
    SHA1 sha = new SHA1Managed();
    byte[] hash = sha.ComputeHash(Encoding.ASCII.GetBytes(stringToHash));

    StringBuilder stringBuilder = new StringBuilder();
    foreach (byte b in hash)
    {
     stringBuilder.AppendFormat("{0:x2}", b);
    }

    return stringBuilder.ToString().ToUpper(); // HashPasswordForStoringInConfigFile uses uppercase hex
}

You'd use it like this:

string salt = "abcdef"; // swap this with a random string generator
string password = string.Format("{0}{1}", "password", salt).SHA1();
Chris S