I want to use salt and hash to create security login. I try to follow this tutorial and write own code but it always return false. Here is my code:
require_once 'application/third_party/Secure-Login/classes/Hashing.php';
require_once 'application/third_party/Secure-Login/classes/Salt.php';
$password = Hashing::create_hash('123456', Salt::random(12));
$old = '$2a$10$zuzycDw3Ack2cCoL3ds1sudJ2WioZ87.75ErLZVcZyh4d1hS2rHFu';
if (Hashing::validate($password, $old, Salt::random(12))) {
echo true;
} else {
echo false;
}
And two classes I included:
<?php
class Hashing {
function __construct() {}
/**
* @param string $pass The user submitted password
* @param string $hashed_pass The hashed password pulled from the database
* @param string $salt The salt pulled from the database
* @param string $hash_method The hashing method used to generate the hashed password
*/
static function validate($pass, $hashed_pass, $salt, $hash_method = 'sha1') {
if (function_exists('hash') && in_array($hash_method, hash_algos())) {
return ($hashed_pass === hash($hash_method, $salt . $pass));
}
return ($hashed_pass === sha1($salt . $pass));
}
/**
* Generates a secure, pseudo-random password with a safe fallback.
*/
static function pseudo_rand($length) {
if (function_exists('openssl_random_pseudo_bytes')) {
$is_strong = false;
$rand = openssl_random_pseudo_bytes($length, $is_strong);
if ($is_strong === true) {
return $rand;
}
}
$rand = '';
$sha = '';
for ($i = 0; $i < $length; $i++) {
$sha = hash('sha256', $sha . mt_rand());
$chr = mt_rand(0, 62);
$rand .= chr(hexdec($sha[$chr] . $sha[$chr + 1]));
}
return $rand;
}
/**
* Creates a very secure hash. Uses blowfish by default with a fallback on SHA512.
*/
static function create_hash($string, $salt = '', $hash_method = 'sha1', $stretch_cost = 10) {
$salt = Hashing::pseudo_rand(128);
$salt = substr(str_replace('+', '.', base64_encode($salt)), 0, 22);
if (function_exists('hash') && in_array($hash_method, hash_algos())) {
return crypt($string, '$2a$' . $stretch_cost . '$' . $salt);
}
return Hashing::_create_hash($string, $salt);
}
/**
* Fall-back SHA512 hashing algorithm with stretching.
*/
static function _create_hash($password, $salt) {
$hash = '';
for ($i = 0; $i < 20000; $i++) {
$hash = hash('sha512', $hash . $salt . $password);
}
return $hash;
}
}
<?php
class Salt {
public static function random($len = 8) {
$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`~!@#$%^&*()-=_+';
$l = strlen($chars) - 1;
$str = '';
for ($i = 0; $i < $len; ++$i) {
$str .= $chars[rand(0, $l)];
}
return $str;
}
}
Please check help me! I don't know where is wrong and how it works. Thank so much!