简体   繁体   中英

Where do I hash the password?

I'm using MVC and I want to know at which point do I hash the user password:

  1. before sending to the server (view)
  2. in the server, when I set the object field (model)
  3. in the server, when I send the object to the controller (controller)
  4. in the server, when I prepare the statements (controller)
  5. in the database,

eg using "set password = sha256(:password)" in the statement

I'm kind of confused, I've been always hashing the password when I create the object and set the field "password" but I've read somewhere it's not safe enough. I'm not sure.

  • In the view: This is too high up. There will almost certainly be multiple views in your application which do things with passwords (two simple ones: login form and password change form), and having password hashing in the view would lead to duplication.

  • In the database: Too low down. The database should never see plaintext passwords; doing this could, in some situations, end up sending plaintext passwords over the network, displaying them in error messages, or writing them to database logs. Moreover, most of the hash functions supported by databases are too fast to be secure for password storage.

  • In the model: Just right. I'd recommend implementing methods on the user object resembling:

     $user->setPassword($password) # sets password to specified value $user->passwordEquals($password) # returns true if value passed in matches the password 

    Note that none of these methods ever expose the password, or how it's stored -- that's all an implementation detail of the object.

Hash it on the server, as soon as you can. ie. as soon as you receive the request from the client. You have no business with the original password, really. Store the hash, and forget it.

As a rule of thumb, you should treat passwords or hashes of passwords as hot potatoes: You want to stop handling them as soon as possible.

Also, on the off chance that the server process is compromised, you don't want sensitive information lurking in the memory of your server. That's why you should avoid letting the original password linger in the memory for too long.

In the domain object that represents to logic use User entity. That's within model layer.

Also, SHA256 should not be considered good enough. Should should be using bcrypt . Preferably with crypt() function.

First get the value in that field. Then apply the hash function. Do the above operations in your controller and then call the model to store in the database. It will give you a better understanding.

(I'm not an expert... pleasure to share my information.. :)

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