1
In my script I use the bcrypt function (through a class), and I have the following problem: At the time I perform the last queries before login I need to make the query where the encrypted email and password are equal to the bank’s email and password, but how do I do that? Since bcrypt uses a salt and generates random values every time a password is encrypted. Translating to MD5 would be more or less like what I wanted:
<?php 
 $email = "[email protected]";
 $senha = "123";
 $senhaCript= md5($senha);
 $select = (Select ... WHERE email = $email && senha = $senhaCript);
And so on, but the problem is that if I encrypt the password with Blowfish, it enters the if block of the invalid password. 
**Detail: to register the user I use the same class
Login check page code:
<?php
session_start();
define('TENTATIVA_LOGIN', 5); 
define('TEMPO_BLOQUEIO', 30); 
require ("bcrypt.php");
require ("conexao.php");
$pdo = conectar();
if (isset($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER'] != "http://localhost:8080/Metta/html/login.php"):
    echo "<script>alert('A requisição não foi feita pelo formulário de login');</script>";
    echo "<script>window.history.back();</script>"; 
    exit();
endif;
$email = trim(strip_tags($_POST['email_form']));
$senha = trim(strip_tags($_POST['senha_form']));
$hashForm = Bcrypt::hash($senha);
$buscaSQL = $pdo->prepare('SELECT email FROM tbl_usuario WHERE email = ?');
$buscaSQL->execute(array($email));
if($buscaSQL->rowCount() <= 0):
    echo "<script>alert('O email digitado: ".$email. " não foi encontrado!');</script>";
    echo "<script>window.history.back();</script>"; 
    exit;
    endif;
$searchSQL = $pdo->prepare('SELECT email,senha FROM tbl_usuario WHERE email = ? && senha = ?');
$searchSQL->execute(array($email, $hashForm));
$linha = $searchSQL->fetch(PDO::FETCH_ASSOC);
$hashDB = $linha['senha'];
if(!(Bcrypt::check($hashForm, $hashDB))):
    echo "<script>alert('Senha inválida para este usuário!');</script>";
    echo "<script>window.history.back();</script>";
    exit;
else:
   echo "<script>alert('Login realizado com sucesso!');</script>";
   //echo "<script>window.location.href='index.php'();</script>";
$resultSQL = $pdo->prepare("SELECT * FROM tbl_usuario WHERE email = ? && senha = ?");
$resultSQL->execute(array($email , $senha));
$row = $resultSQL->fetch(PDO::FETCH_ASSOC);
$_SESSION['login'] = $email;
$_SESSION['cod_usuario'] = $row['cod_usuario'];
$_SESSION['nome'] = $row['nome'];
$_SESSION['tipo'] = $row['tipo'];
$_SESSION['permissoes'] = $row['permissoes'];
$_SESSION['img'] = $row['img'];
$_SESSION['link_box'] = $row['link_box'];
$_SESSION['fk_empresa'] = $row['fk_empresa'];
$_SESSION["logado"] = TRUE;
endif;
?>
Class code:
<?php
class Bcrypt {
/**
 * Default salt prefix
 * 
 * @see http://www.php.net/security/crypt_blowfish.php
 * 
 * @var string
 */
    protected static $_saltPrefix = '2a';
/**
 * Default hashing cost (4-31)
 * 
 * @var integer
 */
    protected static $_defaultCost = 10;
/**
 * Salt limit length
 * 
 * @var integer
 */
    protected static $_saltLength = 22;
/**
 * Hash a string
 * 
 * @param  string  $string The string
 * @param  integer $cost   The hashing cost
 * 
 * @see    http://www.php.net/manual/en/function.crypt.php
 * 
 * @return string
 */
    public static function hash($string, $cost = null) {
        if (empty($cost)) {
            $cost = self::$_defaultCost;
        }
        // Salt
        $salt = self::generateRandomSalt();
        // Hash string
        $hashString = self::__generateHashString((int)$cost, $salt);
        return crypt($string, $hashString);
    }
/**
 * Check a hashed string
 * 
 * @param  string $string The string
 * @param  string $hash   The hash
 * 
 * @return boolean
 */
    public static function check($string, $hash) {
        return (crypt($string, $hash) === $hash);
    }
/**
 * Generate a random base64 encoded salt
 * 
 * @return string
 */
    public static function generateRandomSalt() {
        // Salt seed
        $seed = uniqid(mt_rand(), true);
        // Generate salt
        $salt = base64_encode($seed);
        $salt = str_replace('+', '.', $salt);
        return substr($salt, 0, self::$_saltLength);
    }
/**
 * Build a hash string for crypt()
 * 
 * @param  integer $cost The hashing cost
 * @param  string $salt  The salt
 * 
 * @return string
 */
    private static function __generateHashString($cost, $salt) {
        return sprintf('$%s$%02d$%s$', self::$_saltPrefix, $cost, $salt);
    }
}
Saul, the passwords that are saved in the database have already been encrypted with Blowfish?
– jlHertel
PHP already has the
password_hashthat uses Bcrypt (and in the future Argon2) because it does not use it?– Inkeliz
I think the mistake is
senha = ?, Bcrypt will use another salt, thus generating another "hash", not the same registered.– Inkeliz
@Inkeliz you could give an example?
– UzumakiArtanis