簡體   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