1

我已经编写了一个快速控制台应用程序,可以快速为我的 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 相同的结果。我不是具有微薄背景的安全专家,而且我的字符集知识更差。我很感激任何帮助。

4

5 回答 5

3

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

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

我相信不同之处在于表单身份验证将其散列为十六进制字符串。

于 2009-08-06T19:58:32.697 回答
3

它似乎对我有用。

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

然后我使用了你的代码片段:

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

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

于 2009-08-06T20:03:43.273 回答
2

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

return MachineKeySection.ByteArrayToHexString(
    SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(password)),
    0
);
于 2009-08-06T20:03:37.283 回答
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();
于 2009-08-18T14:20:25.393 回答
0

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

string hashedPwd = FormsAuthentication.HashPasswordForStoringInConfigFile(saltAndPassword, "SHA1");
于 2009-08-06T20:04:57.703 回答