Search code examples
phpmysqlpassword-hash

Password verify not working with password hash BCRYPT


I'm currently working on a PHP login, the password is encrypted on another file using password_hash('password',PASSWORD_BCRYPT), I'm actually retrieving data from mySQL, and getting data from a AJAX call, but I have declared variables for showing my problem:

<?php
require "modulos/conexion.php";
session_start();
if (!isset($_SESSION['username']) && !isset($_SESSION['userid'])) {
    $usuario = "mariano overs";
    $pass = "1234";
    $passdb = '$2y$10$A1nr4od4OjP0N1hNoB9Seur3OsWzU3ufT4G82XNTLV3'; // equivalent of password_hash('1234',PASSWORD_BCRYPT), this is value from DB
    $sql = 'SELECT id_usua, co_usua, ds_pass FROM dbfar_cabusuarios WHERE co_usua="' . $usuario . '" LIMIT 1';
    if ($res = mysqli_query($GLOBALS['conexion'],$sql)) {
        if (mysqli_num_rows($res) == 1) {
            $usuario = mysqli_fetch_array($res, MYSQLI_ASSOC);
            echo "Contrasena guardada: ". $pass . "<br />Contrasena de la base: " . $usuario['ds_pass'] . "<br />";
            if (password_verify($pass, $passdb)){
                $_SESSION['username'] = $usuario['co_usua'];
                $_SESSION['userid'] = $usuario['id_usua'];
                echo "INICIO SESION CORRECTAMENTE";
            }
            else{
                echo "INICIO SESION NO CORRECTO";
            }

        } else {
            echo "REGISTROS NO CORRECTOS";
        }
    } else {
        echo "USUARIO NO EXISTE";
    }
}

Since I know I get the right value from database, is not the problem there, but on the password_verify function. They are not correctly validated. Is there an additional value I need to include on the password_verify?


Solution

  • The hashed password holds a 60-72 character long string.

    The column needs to be long enough in order to accomodate the hash.

    The manual suggests 255 in order to accomodate for the future.

    You will need to start over and alter your column so that it is long enough.

    Do that, store a new hash and start over.

    60 characters: (from the manual)
    $2y$10$.vGA1O9wmRjrwAVXD98HNOgsNpDczlqm3Jq7KnEd1rVAGv3Fykk1a

    and you have a 50 long: (there you go; too short)

    $2y$10$A1nr4od4OjP0N1hNoB9Seur3OsWzU3ufT4G82XNTLV3

    that tells me that it's been truncated.

    The manual states:

    Caution

    Using the PASSWORD_BCRYPT as the algorithm, will result in the password parameter being truncated to a maximum length of 72 characters.

    Reference:


    As an added bonus:

    Your code is prone to an SQL injection. Best to use a prepared statement.