public
Last active

Django's password hashing ported to PHP

  • Download Gist
hash_password.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
<?php
private function set_password($raw_password) {
/*
Sets the password to a string of random sha1 salt
and encrypted password.
 
Separated by '$'
*/
$salt = substr(sha1(genRandomString().genRandomString()), 0, 5);
$hash = sha1($salt.$raw_password);
$enc_password = $salt.'$'.$hash;
$this->password = $enc_password;
}
 
public function check_password($raw_password, $enc_password) {
/*
Returns a boolean of whether the raw_password was correct.
*/
$pieces = explode('$', $enc_password);
$salt = $pieces[0];
$hash = $pieces[1];
 
if ($hash == sha1($salt.$raw_password))
return true;
else
return false;
}
 
function genRandomString($length = 5) {
$retval = "";
for ($i=0; $i < $length; $i++) {
$retval .= chr(rand(97,122));
}
return $retval;
}

this just saved me a ton of time. THANK YOU so much!

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.