繁体   English   中英

没有ASP.NET的FormsAuthentication,在C#Windows应用程序中进行密码散列?

[英]Password hashing in a C# Windows app, absent ASP.NET's FormsAuthentication?

我的Win表单应用程序似乎不喜欢FormsAuthentication,我对哈希很新,所以任何转换它的帮助都会非常受欢迎。 谢谢。

//Write hash
protected TextBox tbPassword;
protected Literal liHashedPassword;

{
  string strHashedPassword = FormsAuthentication.HashPasswordForStoringInConfigFile(tbPassword.Text, "sha1");
  liHashedPassword.Text = "Hashed Password is: " + strHashedPassword;    
}

//read hash
string strUserInputtedHashedPassword = FormsAuthentication.HashPasswordForStoringInConfigFile( tbPassword.Text, "sha1");
if(strUserInputtedHashedPassword == GetUsersHashedPasswordUsingUserName(tbUserName.Text))
{
  // sign-in successful
}
else
{
  // sign-in failed
}
using System.Security.Cryptography;

public static string EncodePasswordToBase64(string password)
{  byte[] bytes   = Encoding.Unicode.GetBytes(password);
   byte[] inArray = HashAlgorithm.Create("SHA1").ComputeHash(bytes);
   return Convert.ToBase64String(inArray);
}  

FormsAuthentication在System.Web.Security命名空间中定义,该命名空间位于System.Web.dll程序集中。

仅仅因为您正在编写WinForm应用程序并不会阻止您使用该命名空间或引用该程序集; 默认情况下它们不会像WebForms应用程序那样完成。

如果您正在使用哈希来获取用户凭据,我建议您不仅要进行哈希处理,理想情况下还需要进行键拉伸。

这是一个以安全的方式执行您想要的API:

https://sourceforge.net/projects/pwdtknet/

我认为它应该有效。 您需要做的就是在代码中引用System.Web.Security(并将其作为Visual Studio项目中的引用添加)。

如果你真的必须'运送'这个表单应用程序,可能添加System.Web.Security不是一个好主意...

如果你需要一个SHA1哈希,有一个非常容易使用的.net加密库,在msdn上有例子。 关键是要

  1. 拿你想要加密的东西
  2. 无论您使用哪种编码(ascii,utf *),都将其转换为字节
  3. 使用内置于.Net的许多散列方案之一来获取散列字节
  4. 将这些字节转换回与步骤2中相同编码的字符串
  5. 将生成的散列字符串保存在某处以供稍后比较

//step 1 and 2
byte[] data = System.Text.Encoding.Unicode.GetBytes(tbPassword.Text,);
byte[] result; 

//step 3
SHA1 sha = new SHA1CryptoServiceProvider(); 
result = sha.ComputeHash(data);

//step 4
string storableHashResult = System.Text.Encoding.Unicode.ToString(result);

//step 5
    // add your code here

你能不能使用BitConverter函数而不是“x2”循环?

例如

return BitConverter.ToString(hash).Replace(“ - ”,“”);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM