passwordHash() – generate salted passwords


/ Published in: PHP
Save to your folder(s)

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


Copy this code and paste it in your HTML
  1. /**
  2.  * Generate salted password, using new salt or exiting one from the password itself.
  3.  *
  4.  * @param string $plainTextPassword
  5.  * @param string $salt default = NULL (create new salt)
  6.  * @param int $saltLength default = 9 (the salt is the first X chars of the password hash)
  7.  * @return string password-hash
  8.  */
  9. function passwordHash( $plainTextPassword, $salt = null, $saltLength = 9 )
  10. {
  11. if( is_null( $salt ) )
  12. {
  13. // create new salt
  14. $salt = substr( sha1( uniqid( mt_rand(), true) ), 0, $saltLength );
  15. }
  16. else
  17. {
  18. $salt = substr( $salt, 0, $saltLength );
  19. }
  20. return $salt . hash( 'sha256', $salt . $plainTextPassword );
  21. }
  22.  
  23.  
  24. /* create new password */
  25. $newPassword = passwordHash( 'plaintext_password_from_user_input', null );
  26.  
  27.  
  28. /* check given plaintext password against hashed one from database */
  29. // query the password hash from the database; $row is a single result row
  30. if( $row['password'] == passwordHash( 'plaintext_password_from_user_input', $row['password'] ) )
  31. {
  32. /* the users password was correct, login successful */
  33. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.