什么会给我与非Web应用程序的FormsAuthentication哈希相同的结果?

时间:2009-08-06 19:55:44

标签: asp.net security console-application

我已经编写了一个快速控制台应用程序,可以快速为我的Web应用程序生成用户名和登录名,而这些帐户没有正确的哈希密码。在我的Web应用程序中,我使用FormsAuthentication,如下所示:

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

我尝试在控制台应用中使用FormsAuthentication,但它无法解析FormsAuthentication和导入。我得到的警告询问我是否错过了装配。我尝试使用以下内容给我与上一个相同的结果:

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;

这两种方法给了我不同的结果。我需要获得与FormsAuthentication相同的结果。我不是一个具有微小背景的安全专家,我的角色设置知识更糟糕。我倾向于任何帮助。

5 个答案:

答案 0 :(得分:3)

以下是如何匹配格式的一个很好的解释。希望能帮助到你。

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

我认为区别在于表单身份验证将其哈希到十六进制字符串。

答案 1 :(得分:3)

这似乎对我有用。

  • 我添加了对System.Web
  • 的引用
  • 我添加了使用System.Web.Security

然后我使用了您的代码段:

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

获得结果。这是在控制台应用程序中。

答案 2 :(得分:2)

如果您很好奇,该方法使用的代码是:

return MachineKeySection.ByteArrayToHexString(
    SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(password)),
    0
);

答案 3 :(得分:2)

这是在C#中避免System.Web.dll依赖的另一种解决方案:

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
}

你会这样使用它:

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

答案 4 :(得分:0)

我能够将System.Web引用添加到控制台应用程序并使用

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