Password storing/checking class. Keeping passwords safe.


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

Nice implementation of Blowfish for storing user passwords to prevent decryption when for example the user database is compromised. Origin: Burak Guzel@Nettuts


Copy this code and paste it in your HTML
  1. //
  2. // PassHash.php (Utility class):
  3. //
  4. class PassHash {
  5.  
  6. // blowfish
  7. private static $algo = '$2a';
  8.  
  9. // cost parameter
  10. private static $cost = '$10';
  11.  
  12.  
  13. // mainly for internal use
  14. public static function unique_salt() {
  15. return substr(sha1(mt_rand()),0,22);
  16. }
  17.  
  18. // this will be used to generate a hash
  19. public static function hash($password) {
  20.  
  21. return crypt($password,
  22. self::$algo .
  23. self::$cost .
  24. '$' . self::unique_salt());
  25.  
  26. }
  27.  
  28.  
  29. // this will be used to compare a password against a hash
  30. public static function check_password($hash, $password) {
  31.  
  32. $full_salt = substr($hash, 0, 29);
  33.  
  34. $new_hash = crypt($password, $full_salt);
  35.  
  36. return ($hash == $new_hash);
  37.  
  38. }
  39.  
  40. }
  41.  
  42.  
  43.  
  44. ///////////////////////////////////////////////////////////////////
  45. //
  46. // Usage during registration (creating a new user record) :
  47. //
  48. ///////////////////////////////////////////////////////////////////
  49.  
  50. // include the class
  51. require ("PassHash.php");
  52.  
  53. // read all form input from $_POST
  54. // ...
  55.  
  56. // do your regular form validation stuff
  57. // ...
  58.  
  59. // hash the password
  60. $pass_hash = PassHash::hash($_POST['password']);
  61.  
  62. // store all user info in the DB, excluding $_POST['password']
  63. // store $pass_hash instead
  64. // ...
  65.  
  66.  
  67.  
  68. ///////////////////////////////////////////////////////////////////
  69. //
  70. // Usage during login (checking the user record) :
  71. //
  72. ///////////////////////////////////////////////////////////////////
  73.  
  74. // include the class
  75. require ("PassHash.php");
  76.  
  77. // read all form input from $_POST
  78. // ...
  79.  
  80. // fetch the user record based on $_POST['username'] or similar
  81. // ...
  82.  
  83. // check the password the user tried to login with
  84. if (PassHash::check_password($user['pass_hash'], $_POST['password'])) {
  85. // grant access
  86. // ...
  87. } else {
  88. // deny access
  89. // ...
  90. }

URL: http://net.tutsplus.com/tutorials/php/understanding-hash-functions-and-keeping-passwords-safe/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.