Search code examples
phpmysqlencryptionsha512dovecot

Dovecot SHA512-Crypt and PHP


I've used the following instructions to install a mail server: http://www.geoffstratton.com/ubuntu-mail-server-postfix-dovecot-and-mysql

Now I'm trying to program a login form in PHP but don't know how to compare the entered password with the saved password.

This is the mysql-code for the password encryption:

ENCRYPT('PASSWORD', CONCAT('$6$', SUBSTRING(SHA(RAND()), -16)))

I don't understand how it works because with every call of this function a completely new string is being generated.

This is what I have so far:

crypt($_POST[‘password’], '$6$'.substr(sha1(rand()), 0, 16))

But as I said every time I get a new string.


Solution

  • Use the PHP functions password_hash and password_verify. These functions salt and iterate to provide secure protection.

    See PHP Manual password_hash and password-verify.

    string password_hash ( string $password , integer $algo [, array $options ] )
    

    Returns the hashed password, or FALSE on failure.

    boolean password_verify ( string $password , string $hash )
    

    Returns TRUE if the password and hash match, or FALSE otherwise.

    Example code:

    $hash = password_hash("rasmuslerdorf", PASSWORD_DEFAULT)
    
    if (password_verify('rasmuslerdorf', $hash)) {
        echo 'Password is valid!';
    } else {
        echo 'Invalid password.';
    }
    

    In your case you grab the password hash for that username from the database, and keep it in a variable called $hash. Then you use password_verify() like this:

    password_verify($_POST["password"], $hash)