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