Created
November 7, 2013 14:33
-
-
Save feeela/7355505 to your computer and use it in GitHub Desktop.
passwordHash() – generate salted passwords Simple password hashing function without recursion using a salt, that is stored together with the password.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Generate salted password, using new salt or exiting one from the password itself. | |
* | |
* @param string $plainTextPassword | |
* @param string $salt default = NULL (create new salt) | |
* @param int $saltLength default = 9 (the salt is the first X chars of the password hash) | |
* @return string password-hash | |
*/ | |
function passwordHash( $plainTextPassword, $salt = null, $saltLength = 9 ) | |
{ | |
if( is_null( $salt ) ) | |
{ | |
/* create new salt */ | |
$salt = substr( sha1( uniqid( mt_rand(), true) ), 0, $saltLength ); | |
} | |
else | |
{ | |
$salt = substr( $salt, 0, $saltLength ); | |
} | |
return $salt . hash( 'sha256', $salt . $plainTextPassword ); | |
} | |
/* create new password */ | |
$newPassword = passwordHash( 'plaintext_password_from_user_input', null ); | |
/* check given plaintext password against hashed one from database; | |
* query the password hash from the database; $row is a single result row */ | |
if( $row['password'] == passwordHash( 'plaintext_password_from_user_input', $row['password'] ) ) | |
{ | |
/* the users password was correct, login successful */ | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment