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

asp.netasp.net-membershipmembershippasswords

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 generate 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.

Best Answer

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
}
Related Topic