I’m using MVC and I want to know at which point do I hash the user password:
- before sending to the server (view)
- in the server, when I set the object field (model)
- in the server, when I send the object to the controller (controller)
- in the server, when I prepare the statements (controller)
- in the database,
e.g. 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:
Note that none of these methods ever expose the password, or how it’s stored — that’s all an implementation detail of the object.