hash() public static method

Using this function is the proper way to hash a password. Using naïve methods such as sha1 or md5, as is done in many web applications, is improper due to the lack of a cryptographically strong salt. Using lithium\security\Password::hash() ensures that: - Two identical passwords will never use the same salt, thus never resulting in the same hash; this prevents a potential attacker from compromising user accounts by using a database of most commonly used passwords. - The salt generator's count iterator can be increased within Lithium or your application as computer hardware becomes faster; this results in slower hash generation, without invalidating existing passwords. Usage: Hash a password before storing it: $hashed = Password::hash($password); Check a password by comparing it to its hashed value: $check = Password::check($password, $hashed); Use a stronger custom salt: $salt = Password::salt('bf', 16); // 2^16 iterations $hashed = Password::hash($password, $salt); // Very slow $check = Password::check($password, $hashed); // Very slow Forward/backward compatibility $salt1 = Password::salt('bf', 6); $salt2 = Password::salt('bf', 12); $hashed1 = Password::hash($password, $salt1); // Fast $hashed2 = Password::hash($password, $salt2); // Slow $check1 = Password::check($password, $hashed1); // True $check2 = Password::check($password, $hashed2); // True
See also: lithium\security\Password::check()
See also: lithium\security\Password::salt()
public static hash ( string $password, string $salt = null ) : string
$password string The password to hash.
$salt string Optional. The salt string.
return string The hashed password. The result's length will be: - 60 chars long for Blowfish hashes - 20 chars long for XDES hashes - 34 chars long for MD5 hashes
 public function generatePassword($entity)
 {
     $newPassword = substr(md5(rand() . rand()), 0, 8);
     $entity->prv_secret = Password::hash($newPassword);
     Logger::debug("New Password for " . $entity->prv_uid . ": {$newPassword} (hash: {$entity->prv_secret})");
     return $newPassword;
 }
Beispiel #2
0
	public static function validatorTest(array $options = array()) {
		return new Record(array('data' => array(
			'username' => 'Bob',
			'password' => Password::hash('s3cure'),
			'group' => 'editors'
		)));
	}
Beispiel #3
0
 public static function find($type = 'all', array $options = array())
 {
     $result = array();
     $users = array(array('id' => 1, 'username' => 'user1', 'email' => '*****@*****.**', 'password' => Password::hash('user1')), array('id' => 2, 'username' => 'user2', 'email' => '*****@*****.**', 'password' => Password::hash('user2')), array('id' => 3, 'username' => 'user3', 'email' => '*****@*****.**', 'password' => Password::hash('user3')));
     switch ($type) {
         case 'first':
             if ($options['conditions']) {
                 $conditions = '';
                 foreach ($options['conditions'] as $key => $condition) {
                     !$conditions || ($conditions .= ' && ');
                     $comparation = '==';
                     if (is_array($condition)) {
                         $keys = array_keys($condition);
                         $comparation = $keys[0];
                         $condition = $condition[$keys[0]];
                     }
                     $conditions .= "\$user['{$key}'] {$comparation} '{$condition}'";
                 }
                 $eval = "return ({$conditions});";
                 foreach ($users as $user) {
                     if (eval($eval)) {
                         $result[] = $user;
                     }
                 }
                 if ($result) {
                     return new Record(array('data' => $result[0], 'model' => __CLASS__));
                 }
                 return null;
             }
             return new Record(array('data' => $users[0], 'model' => __CLASS__));
         case 'all':
         default:
             return new Record(array('data' => $users, 'model' => __CLASS__));
     }
 }
Beispiel #4
0
 /**
  * testPasswordMaxLength method
  */
 public function testPasswordMaxLength()
 {
     foreach (array('bf' => 72) as $method => $length) {
         $salt = Password::salt($method);
         $pass = str_repeat('a', $length);
         $this->assertIdentical(Password::hash($pass, $salt), Password::hash($pass . 'a', $salt));
     }
 }
 /**
  * Tests that a random sequence of keys and tokens properly match one another.
  */
 public function testKeyMatching()
 {
     for ($i = 0; $i < 4; $i++) {
         $token = RequestToken::get(array('regenerate' => true));
         for ($j = 0; $j < 4; $j++) {
             $key = Password::hash($token);
             $this->assertTrue(RequestToken::check($key));
         }
     }
 }
Beispiel #6
0
 public function testConfirm()
 {
     $validate = Validator::check(array('password' => 'user5', 'confirm_password' => 'user5'), array('confirm_password' => array('confirm', 'message' => 'Please confirm your password!')));
     $this->assertTrue(empty($validate));
     $validate = Validator::check(array('password' => 'user5', 'confirm_password' => 'user4'), array('confirm_password' => array('confirm', 'message' => 'Please confirm your password!')));
     $this->assertTrue(!empty($validate));
     $validate = Validator::check(array('password' => Password::hash('user5'), 'confirm_password' => 'user5'), array('confirm_password' => array('confirm', 'message' => 'Please confirm your password!', 'strategy' => 'password')));
     $this->assertTrue(empty($validate));
     $validate = Validator::check(array('password' => Password::hash('user5'), 'confirm_password' => 'user4'), array('confirm_password' => array('confirm', 'message' => 'Please confirm your password!', 'strategy' => 'password')));
     $this->assertTrue(!empty($validate));
     $validate = Validator::check(array('original_password' => 'user5', 'confirm_password' => 'user5'), array('confirm_password' => array('confirm', 'message' => 'Please confirm your password!', 'against' => 'original_password')));
     $this->assertTrue(empty($validate));
     $validate = Validator::check(array('original_password' => 'user5', 'confirm_password' => 'user4'), array('confirm_password' => array('confirm', 'message' => 'Please confirm your password!', 'against' => 'original_password')));
     $this->assertTrue(!empty($validate));
 }
Beispiel #7
0
 /**
  * Apply proper password hashing (on create or change password)
  * On create:
  * 	- apply defined default user group (LI3_UM_DefaultUserGroup)
  * 	- apply defined active status (LI3_UM_RequireUserActivation)
  * 	  0 - require user to activate account trough generated link with token
  *    1 - don't require further actions, account is already activated
  */
 public static function __init()
 {
     static::applyFilter('save', function ($self, $params, $chain) {
         if ($params['data']) {
             $params['entity']->set($params['data']);
             $params['data'] = array();
         }
         if (!$params['entity']->exists()) {
             if ($params['entity']->password) {
                 $params['entity']->password = Password::hash($params['entity']->password);
             }
             $params['entity']->active = 1;
             if (LI3_UM_RequireUserActivation && $self::$request) {
                 $params['entity']->active = 0;
             }
             $params['entity']->user_group_id = LI3_UM_DefaultUserGroup;
         } else {
             if ($params['entity']->password && $params['entity']->modified('password')) {
                 $params['entity']->password = Password::hash($params['entity']->password);
             }
         }
         return $chain->next($self, $params, $chain);
     });
     static::applyFilter('save', function ($self, $params, $chain) {
         if (($save = $chain->next($self, $params, $chain)) && $params['options']['events'] === 'create') {
             $user = $params['entity'];
             AboutUsers::create(array('user_id' => $user->id))->save();
             if (LI3_UM_RequireUserActivation && $self::$request) {
                 $token = Token::generate($user->email);
                 UserActivations::create(array('user_id' => $user->id, 'token' => $token))->save();
                 $link = Router::match(array('li3_usermanager.Users::activate', 'id' => $user->id, 'token' => $token), $self::$request, array('absolute' => true));
                 Mailer::$_data['subject'] = 'Your activation link!';
                 Mailer::$_data['from'] = LI3_UM_ActivationEmailFrom;
                 Mailer::$_data['to'] = $user->email;
                 Mailer::$_data['body'] = 'This is your activation link:' . "\n" . $link;
             }
         }
         return $save;
     });
 }
 /**
  * Tests salting passwords with the MD5 algorithm.
  */
 public function testSaltMD5()
 {
     $this->skipIf(!CRYPT_MD5, 'MD5 is not supported.');
     $saltPattern = "{^\\\$1\\\$[0-9A-Za-z./]{8}\$}";
     $hashPattern = "{^\\\$1\\\$[0-9A-Za-z./]{8}\\\$[0-9A-Za-z./]{22}\$}";
     $salt = Password::salt('md5', null);
     $this->assertPattern($saltPattern, $salt);
     $this->assertNotEqual($salt, Password::salt('md5', null));
     $hash = Password::hash($this->_password, $salt);
     $hash2 = Password::hash($this->_password, Password::salt('md5', null));
     $this->assertPattern($hashPattern, $hash);
     $this->assertNotEqual($hash, $hash2);
 }
Beispiel #9
0
 /**
  * Generates a single-use key to be embedded in a form or used with another non-idempotent
  * request (a request that changes the state of the server or application), that will match
  * against a client session token using the `check()` method.
  *
  * @see lithium\security\validation\RequestToken::check()
  * @param array $options An array of options to be passed to `RequestToken::get()`.
  * @return string Returns a hashed key string for use with `RequestToken::check()`.
  */
 public static function key(array $options = array())
 {
     return Password::hash(static::get($options));
 }
<?php

use app\models\Users;
use lithium\security\Password;
Users::applyFilter('save', function ($self, $params, $chain) {
    if ($params['data']) {
        $params['entity']->set($params['data']);
        $params['data'] = array();
    }
    if (!$params['entity']->exists()) {
        $params['entity']->password = Password::hash($params['entity']->password);
    }
    return $chain->next($self, $params, $chain);
});
Beispiel #11
0
 public static function __init()
 {
     /*
      * Some special validation rules
      */
     Validator::add('uniqueEmail', function ($value) {
         $current_user = Auth::check('li3b_user');
         if (!empty($current_user)) {
             $user = User::find('first', array('fields' => array('_id'), 'conditions' => array('email' => $value, '_id' => array('$ne' => new MongoId($current_user['_id'])))));
         } else {
             $user = User::find('first', array('fields' => array('_id'), 'conditions' => array('email' => $value)));
         }
         if (!empty($user)) {
             return false;
         }
         return true;
     });
     Validator::add('notEmptyHash', function ($value) {
         if ($value == Password::hash('')) {
             return false;
         }
         return true;
     });
     Validator::add('moreThanFive', function ($value) {
         if (strlen($value) < 5) {
             return false;
         }
         return true;
     });
     Validator::add('notTooLarge', function ($value) {
         if ($value == 'TOO_LARGE.jpg') {
             return false;
         }
         return true;
     });
     Validator::add('invalidFileType', function ($value) {
         if ($value == 'INVALID_FILE_TYPE.jpg') {
             return false;
         }
         return true;
     });
     parent::__init();
     /*
      * If told to ues a specific connection, do so.
      * Otherwise, use the default li3b_users connection.
      * Note: This model requires MongoDB.
      * Also note: This must be called AFTER parent::__init()
      *
      * This is useful if the main application also uses MongoDB
      * and wishes everything to use the same database...Be it
      * local or on something like MongoLab or wherever.
      *
      * In fact, when gluing together libraries, one may choose
      * all libraries that use the same database and kinda go
      * with each other. That way it'll end up looking like a single
      * cohesive application from the database's point of view.
      * Of course the it's difficult to avoid conflicts in the MongoDB
      * collection names. In this case, this model is prefixing the
      * library name to the collection in order to ensure there are
      * no conflicts.
      */
     $libConfig = Libraries::get('li3b_users');
     $connection = isset($libConfig['useConnection']) ? $libConfig['useConnection'] : 'li3b_users';
     static::meta('connection', $connection);
 }
 /**
  * Allows a user to update their own profile.
  *
  */
 public function update()
 {
     if (!$this->request->user) {
         FlashMessage::write('You must be logged in to do that.', 'default');
         return $this->redirect('/');
     }
     // Special rules for user creation (includes unique e-mail)
     $rules = array('email' => array(array('notEmpty', 'message' => 'E-mail cannot be empty.'), array('email', 'message' => 'E-mail is not valid.'), array('uniqueEmail', 'message' => 'Sorry, this e-mail address is already registered.')));
     // Get the document from the db to edit
     $conditions = array('_id' => $this->request->user['_id']);
     $document = User::find('first', array('conditions' => $conditions));
     $existingProfilePic = !empty($document->profilePicture) ? $document->profilePicture : false;
     // Redirect if invalid user...This should not be possible.
     if (empty($document)) {
         FlashMessage::write('You must be logged in to do that.', 'default');
         return $this->redirect('/');
     }
     // If data was passed, set some more data and save
     if ($this->request->data) {
         // CSRF
         if (!RequestToken::check($this->request)) {
             RequestToken::get(array('regenerate' => true));
         } else {
             $now = new MongoDate();
             $this->request->data['modified'] = $now;
             // Add validation rules for the password IF the password and password_confirm field were passed
             if (isset($this->request->data['password']) && isset($this->request->data['passwordConfirm']) && (!empty($this->request->data['password']) && !empty($this->request->data['passwordConfirm']))) {
                 $rules['password'] = array(array('notEmpty', 'message' => 'Password cannot be empty.'), array('notEmptyHash', 'message' => 'Password cannot be empty.'), array('moreThanFive', 'message' => 'Password must be at least 6 characters long.'));
                 // ...and of course hash the password
                 $this->request->data['password'] = Password::hash($this->request->data['password']);
             } else {
                 // Otherwise, set the password to the current password.
                 $this->request->data['password'] = $document->password;
             }
             // Ensure the unique e-mail validation rule doesn't get in the way when editing users
             // So if the user being edited has the same e-mail address as the POST data...
             // Change the e-mail validation rules
             if (isset($this->request->data['email']) && $this->request->data['email'] == $document->email) {
                 $rules['email'] = array(array('notEmpty', 'message' => 'E-mail cannot be empty.'), array('email', 'message' => 'E-mail is not valid.'));
             }
             // Set the pretty URL that gets used by a lot of front-end actions.
             // Pass the document _id so that it doesn't change the pretty URL on an update.
             $this->request->data['url'] = $this->_generateUrl($document->_id);
             // Do not let roles or user active status to be adjusted via this method.
             if (isset($this->request->data['role'])) {
                 unset($this->request->data['role']);
             }
             if (isset($this->request->data['active'])) {
                 unset($this->request->data['active']);
             }
             // Profile Picture
             if (isset($this->request->data['profilePicture']['error']) && $this->request->data['profilePicture']['error'] == UPLOAD_ERR_OK) {
                 $rules['profilePicture'] = array(array('notTooLarge', 'message' => 'Profile picture cannot be larger than 250px in either dimension.'), array('invalidFileType', 'message' => 'Profile picture must be a jpg, png, or gif image.'));
                 list($width, $height) = getimagesize($this->request->data['profilePicture']['tmp_name']);
                 // Check file dimensions first.
                 // TODO: Maybe make this configurable.
                 if ($width > 250 || $height > 250) {
                     $this->request->data['profilePicture'] = 'TOO_LARGE.jpg';
                 } else {
                     // Save file to gridFS
                     $ext = substr(strrchr($this->request->data['profilePicture']['name'], '.'), 1);
                     switch (strtolower($ext)) {
                         case 'jpg':
                         case 'jpeg':
                         case 'png':
                         case 'gif':
                         case 'png':
                             $gridFile = Asset::create(array('file' => $this->request->data['profilePicture']['tmp_name'], 'filename' => (string) uniqid(php_uname('n') . '.') . '.' . $ext, 'fileExt' => $ext));
                             $gridFile->save();
                             break;
                         default:
                             $this->request->data['profilePicture'] = 'INVALID_FILE_TYPE.jpg';
                             //exit();
                             break;
                     }
                     // If file saved, set the field to associate it (and remove the old one - gotta keep it clean).
                     if (isset($gridFile) && $gridFile->_id) {
                         if ($existingProfilePic && substr($existingProfilePic, 0, 4) != 'http') {
                             $existingProfilePicId = substr($existingProfilePic, 0, -strlen(strrchr($existingProfilePic, '.')));
                             // Once last check...This REALLY can't be empty, otherwise it would remove ALL assets!
                             if (!empty($existingProfilePicId)) {
                                 Asset::remove(array('_id' => $existingProfilePicId));
                             }
                         }
                         // TODO: Maybe allow saving to disk or S3 or CloudFiles or something. Maybe.
                         $this->request->data['profilePicture'] = (string) $gridFile->_id . '.' . $ext;
                     } else {
                         if ($this->request->data['profilePicture'] != 'INVALID_FILE_TYPE.jpg') {
                             $this->request->data['profilePicture'] = null;
                         }
                     }
                 }
             } else {
                 $this->request->data['profilePicture'] = null;
             }
             // Save
             if ($document->save($this->request->data, array('validate' => $rules))) {
                 FlashMessage::write('You have successfully updated your user settings.', 'default');
                 $this->redirect(array('library' => 'li3b_users', 'controller' => 'users', 'action' => 'update'));
             } else {
                 $this->request->data['password'] = '';
                 FlashMessage::write('There was an error trying to update your user settings, please try again.', 'default');
             }
         }
     }
     $this->set(compact('document'));
 }