I'm looking for a reliable solution to compare two strings without leaking their content through time differences. The length of the strings is not secret.
The background is this: I'm implementing password-based authentication for a web application. The passwords are hashed with bcrypt and stored in a database. Rather than giving the application direct access to the hashes so that it check the password, I'd like to delegate this to the database system itself. The application only hashes the password and then passes the hash to a database procedure. This procedure has special privileges to access the stored hashes and compare them with the provided hash. The goal is to protect the hashes against SQL injection attacks. A similar idea is described in this presentation.
Obviously, this scheme is only effective if the procedure does not leak any information about the stored hashes. So the string comparison must be timing-safe.
I'm aware of the following method (pseudo-code):
string_comp(str_1, str_2): if str_1.length != str_2.length: return false else: result := 0 for i := 0 to str_1.length - 1: result := result | (str_1[i] ^ str_2[i]) return result == 0
However, this is rather cumbersome, and I'm not sure if it works as expected in high-level languages like SQL.
Another common suggestion is to hash the strings and then compare the hashes. This would be much simpler than the code above.
Which method is preferable? If I were to use the hash solution, which algorithm would I choose to not degrade the strength of bcrypt (not even theoretically)? SHA-256? SHA-384? SHA-512?