User Login with a single query and per-user password salt

纵然是瞬间 提交于 2019-12-04 11:59:02

You could accomplish this in one query like this:

SELECT 
   SHA1(CONCAT(users.salt, "password-input")) = users.passwordhash
WHERE 
   username = "username-input"

...and which is the server in 'in the server-side code (PHP)'? I come from a world where the DBMS is the server and everything else is the client. I suspect you're looking at a web-server as the 'server-side' and the DBMS as a separate gizmo, not necessarily as a server itself. Ah well, such is the theory of relativity of viewpoints. (And don't get me started on X11 servers vs clients!)

Yes, it is reasonable to simply collect the salt and the salted, hashed password for the user name in a single operation, and then generate the SHA result of the provided password and the salt in PHP, comparing it with the retrieved hashed password value. It even means that the password does not travel from the PHP to the database server, so it doesn't matter if that communication is encrypted or not (in the situation where the PHP and the DBMS are not on the same machine). It also offloads the computation from the DBMS to the PHP; whether this is a benefit depends on the relative workloads of the PHP and the DBMS.

As another answer points out, it is possible to get the answer by sending the user's supplied password to the DBMS and having the DBMS do the hash computation. Beware of simply quoting the user's input - escape it to prevent SQL injection. This potentially exposes the password to snooping on the trip from PHP to DBMS. How much that matters depends on your infrastructure.

I think your approach is generally sound. More important than how many queries you use, is whether you are retrieving the valid database password over the wire even when a bad password is input by the user. Your query does this, whereas by making use of an encryption function on your db server, you are avoiding this and making things more secure.

To make it even more secure, use a stored procedure or function that hides the type of encryption (or the fact that any is even being used) from anyone who is sniffing SQL queries over the wire, or through some other means (e.g., causing queries to be visible by using SQL injection vulnerabilities, or by exposing the query in an error message).

I see no drawbacks with it. "gahooa" gave an excellent answer as well. It'll shift the processing cost from your web server to your database server, but that's just a question for you as to which one is better suited to the load.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!