Skip to content

Instantly share code, notes, and snippets.

@staydecent
Created June 10, 2011 20:18
Show Gist options
  • Save staydecent/1019680 to your computer and use it in GitHub Desktop.
Save staydecent/1019680 to your computer and use it in GitHub Desktop.
Django's password hashing ported to PHP
<?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;
}
@jyoungblood
Copy link

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

@ducsatthu
Copy link

Thank you so much !

@isaiasmac
Copy link

This doesn't work on Django 1.9+

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment