Problem with User Password Validation (php, mysql, crypt)

1

I'm just trying to validate the password typed with the password stored in the database, and the password stored in the database has been encrypted. The problem is that I type the correct password, my function searches for the correct registry in the bank and returns the encrypted password, however when comparing the passwords they never hit (even though I see that the characters are identical, so much so that I copy and paste it. value received in the bank works). In short, it is as if I compared "abc" == "abc" and it returned false if the second "abc" came from the bank.

public function userAut(){
        $id = [ 0 => 'senha_Admin',
                 'userId']; //enviando as chaves para fazer o select 
        $elemento = $this->adm->getuserid(); //id enviado pelo usuário no formulario
        $hash = $this->bd->select('User_Admin',$id,$elemento); // retorna um array com resultado do select
        $pass = $this->adm->getpass();// senha enviada pelo usuario no formulario
        $id = [ 0=> 'nome_Admin',
                    'userId'];
        $nome = $this->bd->select('User_Admin',$id,$elemento); //retorna o nome do usuario

        $senha_codificada_bd = $hash['senha_Admin']; // senha obtida no bd
        $senha_codificada_informada = crypt($pass, $senha_codificada_bd); //senha informada pelo usuário codificada

        if ($senha_codificada_bd == $senha_codificada_informada) { //comparando as senhas (banco e informada)
            return "Bem Vindo ".$nome['nome_Admin']. " !";
        }else{
            return "Login Invalido ".$senha_codificada_bd;
        }

    }
    
asked by anonymous 04.09.2015 / 17:48

2 answers

2

You have to give crypt in the password passed by the user. Ex:

$password = crypt($this->adm->getpass()); //senha passado pelo usuário do formulario
$senha_codificada_bd = $hash['senha_Admin']; // senha obtida no bd
if (crypt($senha_codificada_bd, $password) == $password) { 
   echo "Password ok!";
}
    
04.09.2015 / 21:39
1

Hello, what I'm going to explain does not differ with any other explanation about Blowfish .

function verifica_hash($password, $hash_existente){
    $hash = crypt($password, $hash_existente);
    if($hash === $hash_existente){
        return true;
    } else {
        return false;
    }
}

This section I pasted above, belongs to a tutorial on Blowfish that I did once.

The function receives 2 argumentos which is the password typed in the form of login , and the password from banco de dados . then we have another variable called $hash :

  

$ hash = crypt ($ password, $ hash_existing);

Which makes use of the crypt function and encrypts the password of the form using password guardada(hash no banco de dados) to create a new hash . And finally times a condition that checks whether the 2 values really match. And if they match, the function returns true , or falso in case it does not match.

Blowfish usually uses the 22 first characters of hash/salt to create another hash . The formato also influences the final result of hash .

Another thing is that Blowfish normally uses 60 positions in the table.

  

hash_password VARCHAR (60)

In all, you simply need to 4 values, which are, the hash and username in the database, and the password and username form.

Examples

Here are some examples of the method (for versions of PHP >=5.5.0 there are functions of their own).

<?php

//blowfish.php
//Funções para quem tem versão d PHP < 5.5.0
// Função que gera a hash
function hash_password($password){
    $formato = custo_recomendado($password);
    $salt = salt(22);
    $formato_salt = $formato.$salt;
    $password_hash = crypt($password, $formato_salt);
    return $password_hash;
    // Se algo correr mal a função vai retornar falso;
}
// Função que gera o salt
function salt($tamanho){
    //$random = md5(uniqid(mt_rand(), true));
    // ambas funções geram valores aleatorios
    $random = md5(uniqid(mcrypt_create_iv(22, MCRYPT_DEV_URANDOM), true));
    $base = base64_encode($random);
    $base64 = str_replace('+', '.', $base);
    $salt = substr($base64, 0, $tamanho);
    return $salt;
}
// Função para comparar as duas hash
function verifica_hash($password, $hash_existente){
    $hash = crypt($password, $hash_existente);
    if($hash === $hash_existente){
        return true;
    } else {
        return false;
    }
}

?>

...

<?php

//database.php
session_start();
require_once("blowfish.php");
// Função para efectuar o registo;
function registar($usuario, $email, $password){
    global $db;
    $password = hash_password($password);
    ($stmt = $db->prepare("INSERT INTO usuarios (username, email, senha) VALUES (?, ?, ?)"))
    || error_logi("SQL Prepared Statment",$db->error);
    ($stmt->bind_param('sss', $usuario, $email, $password)) || error_logi("SQL BindParam",$db->error);
    $exec = $stmt->execute() ? true : error_logi("SQL Execute",$db->error);
    return $exec;
    $stmt->close();
    $db->close();
}
// Tentar fazer o login
function login($usuario, $password){
    $usuario = encontrar_usuario($usuario);
    if($usuario){
        // usuario encontrado
        // Verificar a hash para a password
        if(verifica_hash($password, $usuario["senha"])){
            $_SESSION["usuario"] = $usuario["username"];
            return true;
        } else {
            // hash não encontrada
            return false;
        }
    } else {
        // usuario não encontrado
        return false;
    }
}

function check_login($usuario){
    $existe = encontrar_usuario($usuario);
    if($existe){
        return $existe["username"] === $usuario ? true : false;
    } else {
        return false;
    }
}

?>

...

<?php

//privado.php
// Esta é a página protegida
require_once("database.php");

if(isset($_SESSION["usuario"])){
    if(check_login($_SESSION["usuario"])){
        echo "Logado";
        // Isto é um sistema para teste, daí usar esta função aqui
        // Significa que a página só pode ser visualizada apenas 1 vez por login
        session_destroy();
    } else {
        header("Location:index.php");
        exit;
    }
} else {
    header("Location:index.php");
    exit;
}

?>

...

<?php

//index.php
require("database.php");

if(isset($_POST["submit"]) && isset($_POST["tipo"]) && $_POST["tipo"] === "novo"){
    $usuario = $_POST["usuario"];
    $email = $_POST["email"];
    $password = $_POST["password"];
    if($usuario !== NULL && $password !== NULL){
        $sim = registar($usuario, $email, $password);
        if($sim){
            header("Location: index.php");
            exit;
        } else {
            echo "erro sub";
            exit;
        }
    } else {
        echo "erro";
        exit;
    }
}

if(isset($_POST["submit"]) && isset($_POST["tipo"]) && $_POST["tipo"] === "entrar"){
    $usuario = $_POST["usuario"];
    // $email = $_POST["email"];
    $password = $_POST["password"];
    if($usuario !== NULL && $password !== NULL){
        $sim = login($usuario, $password);
        if($sim){
            header("Location: privado.php");
            exit;
        } else {
            echo "erro subl";
            exit;
        }
    } else {
        echo "errol";
        exit;
    }
}

if(isset($_GET["opcao"]) && $_GET["opcao"] === "login"){
    ?>
    <h1>Login</h1>
    <form method="POST" action="index.php">
        <input type="hidden" name="tipo" value="entrar"/>
        Usuario:<br/>
        <input type="text" name="usuario" value="" size="40"/><br/>
        Password:<br/>
        <input type="password" name="password" value="" size="40"/><br/>

        <input type="submit" name="submit" value="Entrar"/>

    </form>
    <a href="index.php?opcao=novo">Cadastrar</a><br/><br/>
    <?php
} elseif(isset($_GET["opcao"]) && $_GET["opcao"] === "novo"){
    ?>
    <h1>Cadastrar</h1>
    <form method="POST" action="index.php">
        <input type="hidden" name="tipo" value="novo"/>
        Usuario:<br/>
        <input type="text" name="usuario" value="" size="40"/><br/>
        Email:<br/>
        <input type="email" name="email" value="" size="40"/><br/>
        Password:<br/>
        <input type="password" name="password" value="" size="40"/><br/>

        <input type="submit" name="submit" value="Entrar"/>

    </form>
    <a href="index.php?opcao=entrar">Login</a><br/><br/>
    <?php
} else {
    ?>

    <h1>Login</h1>
    <form method="POST" action="index.php">
        <input type="hidden" name="tipo" value="entrar"/>
        Usuario:<br/>
        <input type="text" name="usuario" value="" size="40"/><br/>
        Password:<br/>
        <input type="password" name="password" value="" size="40"/><br/>

        <input type="submit" name="submit" value="Entrar"/>

    </form>
    <a href="index.php?opcao=novo">Cadastrar</a><br/><br/>
    <?php
}

?>
    
05.09.2015 / 01:05