Skip to content

Instantly share code, notes, and snippets.

@mlorant
Created May 18, 2013 16:10
Show Gist options
  • Save mlorant/5604933 to your computer and use it in GitHub Desktop.
Save mlorant/5604933 to your computer and use it in GitHub Desktop.
Advanced method to hash password
<?php
define('SALT_LENGTH', 6);
define('ITERATIONS', 10000);
/** Génère le hash complet d'un mot de passe donné en clair */
function create_hash($password) {
$salt = get_rand_salt();
$hash = get_hash($password, $salt, ITERATIONS);
return ITERATIONS."$".$salt."$".$hash;
}
/** Vérifie si un mot de passe est correct par rapport à un hash */
function check_password($plain, $hash) {
$infos = explode('$', $hash); // Il faudrait vérifier qu'on a bien 3 entrées distincts : nb itérations, sel et hash.
return (get_hash($plain, $infos[1], $infos[0]) == $infos[2]); // Retourne vrai si hash identique
}
/** Génère le hash du mot de passe en fonction du sel et du nombre d'itérations */
function get_hash($password, $salt, $iterations) {
for($i = 0; $i < $iterations; $i++) {
$password = sha1($salt.$password);
}
return $password;
}
function get_rand_salt() {
$car = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
'm', 'n', 'o', 'p', 'r', 's', 't', 'u', 'v', 'x', 'y', 'z',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
'M', 'N', 'O', 'P', 'R', 'S', 'T', 'U', 'V', 'X', 'Y', 'Z',
'1', '2', '3', '4', '5', '6', '7', '8', '9', '0');
$nb_car = count($car) - 1;
$salt = '';
for ($i = 0; $i < SALT_LENGTH; $i++) {
$index = rand(0, $nb_car);
$salt .= $car[$index];
}
return $salt;
}
/** Programme de test */
$hash = create_hash('toto');
echo $hash."\n"; // Retourne 10000$GtHABK$dd920adc528bf09d7a107e2a031b2dff190668fd
var_dump(check_password('toto', $hash)); // Retourne bool(true)
var_dump(check_password('toat', $hash)); // Retourne bool(false)
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment