Return to Snippet

Revision: 58757
at August 1, 2012 19:08 by feeela


Initial Code
/**
 * 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 */
}

Initial URL


Initial Description
Simple password hashing function without recursion using a salt, that is stored together with the password.

Initial Title
passwordHash() – generate salted passwords

Initial Tags


Initial Language
PHP