Skip to content

Instantly share code, notes, and snippets.

@feeela
Created November 7, 2013 14:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save feeela/7355505 to your computer and use it in GitHub Desktop.
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.
/**
* 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