The MySQL ENCRYPT()
function calls the crypt(3) Unix library function, which implements a variety of password hashing algorithms. The specific algorithm to use is selected by the salt
parameter, which should begin with an algorithm identifier surrounded by dollar signs; for example, a salt beginning with $1$
corresponds to the old MD5-based hashing scheme by Poul Henning-Kamp.
(The reason for this rather curious way of selecting the algorithm is historical; the original DES-based crypt(3) design from 1976 didn't support alternative hashing algorithms, so a method for designating them had to be shoehorned into the existing interface in order to retain compatibility with old password databases. As it turns out, the resulting system is quite nice and flexible, even if it looks kind of weird at first glance.)
Anyway, all the crypt(3) hashing algorithms (including the original DES-based one) always include the salt (and the algorithm identifier embedded in it) at the beginning of the output, and ignore any extra data appended to the end of the salt input. Thus, to verify a password hash, you simply feed the original hash into ENCRYPT()
as the salt, and check if it equals the output:
SELECT user_id,
password_hash = ENCRYPT('password', password_hash) AS password_is_correct
FROM user_table WHERE user_id = 12345;