User Password Validation Issue (php, mysql, crypt)

Asked

Viewed 1,217 times

1

I’m just trying to validate the password entered with the password stored in the bank, and the password stored in the bank was encrypted. The problem is that I type the correct password, my function searches the correct record in the database and returns me the encrypted password, but when comparing the passwords they never match (even though I see that the characters are identical, so much so that the copy and paste the value received in the bank works). In short it’s as if I compare "abc" == "abc" and he returned me false if the second "abc" had come 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;
        }

    }

2 answers

2

You have to give one 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!";
}

1

Hello, what I’m going to explain to you is no different than any other explanation about the Blowfish.

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

This excerpt I pasted above, belongs to a tutorial on the Blowfish that I once made.

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

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

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

The 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 the Blowfish usually uses 60 table positions.

hash_password VARCHAR(60)

All in all, you just 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 own functions).

<?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
}

?>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.