开发者

how to reset & change the hash password in asp.net membership provider in MVC

I came accross the code :

MembershipUser u = Membership.GetUser();
u.ChangePassword(u.ResetPassword(), "Password"); //where will I get the "Password" from 

I dont understand how I will get the client password as the user has forgotten his old password. I want to add a reset functionality which would g开发者_C百科enerate a random password and send an email to the particular client which will have the userid and the random generated password. After he/she would be able to change the password.


You can generate a random password like this using the Membership GeneratePassword method

string password = System.Web.Security.Membership.GeneratePassword(14, 0);

If you need to create your own salt and hash a new password, here is an implementation which does much the same as the membership code:

public class Cryptographer : ICryptographer
{
    #region ICryptographer Members

    public string CreateSalt()
    {
        byte[] data = new byte[0x10];
        new RNGCryptoServiceProvider().GetBytes(data);
        return Convert.ToBase64String(data);
    }

    /// <summary>
    /// Hash the password against the salt
    /// </summary>
    /// <param name="pass">Plain password</param>
    /// <param name="salt">Salt string</param>
    /// <returns>Encrypted password</returns>
    public string HashPassword(string password, string salt)
    {
        byte[] bytes = Encoding.Unicode.GetBytes(password);
        byte[] src = Convert.FromBase64String(salt);
        byte[] dst = new byte[src.Length + bytes.Length];
        byte[] inArray = null;
        Buffer.BlockCopy(src, 0, dst, 0, src.Length);
        Buffer.BlockCopy(bytes, 0, dst, src.Length, bytes.Length);
        HashAlgorithm algorithm = HashAlgorithm.Create(System.Web.Security.Membership.HashAlgorithmType);
        inArray = algorithm.ComputeHash(dst);
        return Convert.ToBase64String(inArray);
    }

    #endregion
}


The second paremeter of the ChangePassword method is a string that reprisents the new password you'd like to use for that user.

You can change this to be any string you want, even an auto generated string that you'll email to the user.

UPDATE

To answer your new question, I believe that all hashing of the password etc is handled by the Membership Provider.

If you simply want to reset the users password to a random new value, you might be better using the ResetPassword method instead of ChangePassword.

This will:

Resets a user's password to a new, automatically generated password.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜