简体   繁体   中英

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

My Win form app doesn't seem to like FormsAuthentication, I'm totally new to hashing so any help to convert this would be very welcome. Thanks.

//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);
}  

The FormsAuthentication is defined in the System.Web.Security namespace which is in the System.Web.dll assembly.

Just because you are writing a WinForm app does not stop you from using that namespace or referencing that assembly; they are just not done by default as they would be for a WebForms app.

If you are using the hashing for user credentials I suggest you do more than just hashing, you ideally want key stretching as well.

Here is an API to do what you want in a secure fashion:

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

I think it should work. All you need to do is reference System.Web.Security in your code (and add it as a reference in your Visual Studio Project).

If you actually have to 'ship' this forms app, maybe adding System.Web.Security is not such a good idea...

If you need an SHA1 hash, there is a very easy to use .net cryptography library with examples on msdn. The key is to

  1. take what you want to encrypt
  2. turn it into bytes for whichever encoding(ascii, utf*) you are using
  3. Use one of the many hashing schemes builtin to .Net to get the hashed bytes
  4. turn those bytes back into a string in the same encoding as in step 2
  5. Save the resulting hashed string somewhere for later comparison

//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

Could you not use the BitConverter function instead of the "x2" loop?

eg

return BitConverter.ToString(hash).Replace("-", "");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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