Pete
Pete

Reputation: 2463

MVC Password Property Hash

Im practicing with one way hash encryption.

I have a MVC model with Entity Framework and I wanted to store a password value. I was hoping to have a write only property but what I have found is that if I dont have a return value then it doesn't get stored in the database. Whenever I visit the edit view I see my hash. I was able to work around that by using an empty generic password input field in the edit view.

Now, the problem I now have is if the user wants to edit their information and not change their password (by leaving it blank) it sets the password field to null even though I have not changed the value of that property.

Can anyone suggest a better method? Thanks in advance for your responses.

[DataType(DataType.Password), MaxLength(50)]
    private string _Password;
    public string Password
    {
        get
        {
            return _Password;
        }

        set
        {
            if(!string.IsNullOrEmpty(value))
            {
            _Password = FormsAuthentication.HashPasswordForStoringInConfigFile(value, "MD5");
            }
        }

    }

Upvotes: 1

Views: 2280

Answers (1)

Brent M. Spell
Brent M. Spell

Reputation: 2257

The best way that I've found to do this is to create two properties on your entity class. One of those will represent the hashed password, and it will be read/write, so that EF can round-trip it successfully. It is safe to provide the hashed password as read/write, because it is reasonably infeasible to recover the plaintext from the hash.

The second property should represent the password plaintext, and should be write-only (and ignored by EF). In its setter, you would hash the password and store it in the other property. Only the code that changes the user's password should access this method.

Finally, you should create a Validate() method that accepts the plaintext password, hashes it, and then compares it to the hash property for authentication purposes.

Using this approach, you can apply validation attributes (regex, for example) to enforce password complexity policy on the plaintext write-only property, for binding in your password editor. You can also use the write-only property to generate password history child records, for enforcing password uniqueness and change frequency policy.

In addition, you should salt the password hash (I have done this with user GUIDs in the past), so that the same password used by two different users will not have the same hash value. This can be done by concatenating the password plaintext with a unique but deterministic value associated with the user, before hashing it.

Upvotes: 2

Related Questions