1

I am writing a custom MembershipProvider. Of course I want to encrypt the password the user creates. I presume that .NET has something that encrypts passwords. What is it and how do I use it? What size of string does that output? I have written membership providers before, but it has only been to verify the user is valid. This is the first time I need to add user registration and login.

I am sure I am not using the right search terms, but Google has not shown me anything of value for me.

Mike Wills
  • 20,959
  • 28
  • 93
  • 149

1 Answers1

1

First of all you shouldn't encrypt the passwords. You should hash them (There's an forever going debate about this).

For hashing passwords you could use HMACSHA1. For example when you create the user and before you store the password:

HMACSHA1 hash = new HMACSHA1();
hash.Key = youKey; // you could use machine key
encodedPassword =  Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(password)));

and then store that value in the database. You can then compare the entered password by hashing it and comparing the hashed values.

Of course you need to specify that the password is hashed in the config file:

<membership defaultProvider="SqlProvider" userIsOnlineTimeWindow="20">
  <providers>
    <remove name="AspNetSqlProvider" />
    <add name="SqlProvider"
      type="System.Web.Security.SqlMembershipProvider"
      passwordFormat="Hashed"
      applicationName="/" />
  </providers>
</membership>

Check out my blog post on this. It has an example there using hashed and encrypted passwords.

Community
  • 1
  • 1
TheBoyan
  • 6,802
  • 3
  • 45
  • 61
  • I guess in this case, I am meaning that I don't want to store them in clear text. – Mike Wills Mar 10 '12 at 18:55
  • @MikeWills - I'm not sure I understand what you mean by this, but you would not be storing them in clear text in either case, whether they're encrypted or hashed. – TheBoyan Mar 10 '12 at 18:59
  • Clear text meaning if my password is pass1234, I see pass1234 in the password field. Hashed I would what looks like random gibberish. – Mike Wills Mar 10 '12 at 19:02
  • @MikeWills - If you want to be able to retrieve the password(even though this generally a good idea...) then you can use the EncryptPassword/DecryptPassword from the MembershipProvider class. See the blog post in the answer for an example. – TheBoyan Mar 10 '12 at 19:21