Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add password salts and encrypt with bcrypt #19

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 0 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,6 @@ Change your config main:
'modules'=>array(
#...
'user'=>array(
# encrypting method (php hash function)
'hash' => 'md5',

# send activation email
'sendActivationMail' => true,

Expand Down Expand Up @@ -89,9 +86,6 @@ Change your config console:
'modules'=>array(
#...
'user'=>array(
# encrypting method (php hash function)
'hash' => 'md5',

# send activation email
'sendActivationMail' => true,

Expand Down
21 changes: 13 additions & 8 deletions UserModule.php
Original file line number Diff line number Diff line change
Expand Up @@ -158,18 +158,23 @@ public static function t($str='',$params=array(),$dic='user') {
}

/**
* Encrypt a password.
* @return hash string.
*/
public static function encrypting($string="") {
$hash = Yii::app()->getModule('user')->hash;
if ($hash=="md5")
return md5($string);
if ($hash=="sha1")
return sha1($string);
else
return hash($hash,$string);
$bcrypt = new Bcrypt();
return $bcrypt->hash($string);
}


/**
* Verify if unencrypted password is same as encrypted hash.
* @return boolean
*/
public static function verifyPassword($password, $hash) {
$bcrypt = new Bcrypt();
return $bcrypt->verify($password, $hash);
}

/**
* @param $place
* @return boolean
Expand Down
107 changes: 107 additions & 0 deletions components/Bcrypt.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
<?php

class Bcrypt {
private $rounds;
private $randomState;
public function __construct($rounds = 12) {
if(CRYPT_BLOWFISH != 1) {
throw new Exception("bcrypt not supported in this installation. See http://php.net/crypt");
}

$this->rounds = $rounds;
}

public function hash($input) {
$hash = crypt($input, $this->getSalt());

if(strlen($hash) > 13)
return $hash;

return false;
}

public function verify($input, $existingHash) {
$hash = crypt($input, $existingHash);

return $hash === $existingHash;
}

private function getSalt() {
$salt = sprintf('$2a$%02d$', $this->rounds);

$bytes = $this->getRandomBytes(16);

$salt .= $this->encodeBytes($bytes);

return $salt;
}

private function getRandomBytes($count) {
$bytes = '';

if(function_exists('openssl_random_pseudo_bytes') &&
(strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN')) { // OpenSSL slow on Win
$bytes = openssl_random_pseudo_bytes($count);
}

if($bytes === '' && is_readable('/dev/urandom') &&
($hRand = @fopen('/dev/urandom', 'rb')) !== FALSE) {
$bytes = fread($hRand, $count);
fclose($hRand);
}

if(strlen($bytes) < $count) {
$bytes = '';

if($this->randomState === null) {
$this->randomState = microtime();
if(function_exists('getmypid')) {
$this->randomState .= getmypid();
}
}

for($i = 0; $i < $count; $i += 16) {
$this->randomState = md5(microtime() . $this->randomState);

if (PHP_VERSION >= '5') {
$bytes .= md5($this->randomState, true);
} else {
$bytes .= pack('H*', md5($this->randomState));
}
}

$bytes = substr($bytes, 0, $count);
}

return $bytes;
}

private function encodeBytes($input) {
// The following is code from the PHP Password Hashing Framework
$itoa64 = './ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

$output = '';
$i = 0;
do {
$c1 = ord($input[$i++]);
$output .= $itoa64[$c1 >> 2];
$c1 = ($c1 & 0x03) << 4;
if ($i >= 16) {
$output .= $itoa64[$c1];
break;
}

$c2 = ord($input[$i++]);
$c1 |= $c2 >> 4;
$output .= $itoa64[$c1];
$c1 = ($c2 & 0x0f) << 2;

$c2 = ord($input[$i++]);
$c1 |= $c2 >> 6;
$output .= $itoa64[$c1];
$output .= $itoa64[$c2 & 0x3f];
} while (1);

return $output;
}
}
4 changes: 2 additions & 2 deletions components/UserIdentity.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public function authenticate()
} else {
$this->errorCode=self::ERROR_USERNAME_INVALID;
}
else if(Yii::app()->getModule('user')->encrypting($this->password)!==$user->password)
else if(!Yii::app()->getModule('user')->verifyPassword($this->password, $user->password))
$this->errorCode=self::ERROR_PASSWORD_INVALID;
else if($user->status==0&&Yii::app()->getModule('user')->loginNotActiv==false)
$this->errorCode=self::ERROR_STATUS_NOTACTIV;
Expand All @@ -53,4 +53,4 @@ public function getId()
{
return $this->_id;
}
}
}
4 changes: 2 additions & 2 deletions controllers/ActivationController.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ public function actionActivation () {
if (isset($find)&&$find->status) {
$this->render('/user/message',array('title'=>UserModule::t("User activation"),'content'=>UserModule::t("You account is active.")));
} elseif(isset($find->activkey) && ($find->activkey==$activkey)) {
$find->activkey = UserModule::encrypting(microtime());
$find->activkey = md5(microtime());
$find->status = 1;
$find->save();
$this->render('/user/message',array('title'=>UserModule::t("User activation"),'content'=>UserModule::t("You account is activated.")));
Expand All @@ -28,4 +28,4 @@ public function actionActivation () {
}
}

}
}
6 changes: 3 additions & 3 deletions controllers/AdminController.php
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ public function actionCreate()
if(isset($_POST['User']))
{
$model->attributes=$_POST['User'];
$model->activkey=Yii::app()->controller->module->encrypting(microtime().$model->password);
$model->activkey=md5(microtime().$model->password);
$profile->attributes=$_POST['Profile'];
$profile->user_id=0;
if($model->validate()&&$profile->validate()) {
Expand Down Expand Up @@ -118,7 +118,7 @@ public function actionUpdate()
$old_password = User::model()->notsafe()->findByPk($model->id);
if ($old_password->password!=$model->password) {
$model->password=Yii::app()->controller->module->encrypting($model->password);
$model->activkey=Yii::app()->controller->module->encrypting(microtime().$model->password);
$model->activkey=md5(microtime().$model->password);
}
$model->save();
$profile->save();
Expand Down Expand Up @@ -184,4 +184,4 @@ public function loadModel()
return $this->_model;
}

}
}
4 changes: 2 additions & 2 deletions controllers/ProfileController.php
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ public function actionChangepassword() {
if($model->validate()) {
$new_password = User::model()->notsafe()->findbyPk(Yii::app()->user->id);
$new_password->password = UserModule::encrypting($model->password);
$new_password->activkey=UserModule::encrypting(microtime().$model->password);
$new_password->activkey=md5(microtime().$model->password);
$new_password->save();
Yii::app()->user->setFlash('profileMessage',UserModule::t("New password is saved."));
$this->redirect(array("profile"));
Expand All @@ -102,4 +102,4 @@ public function loadUser()
}
return $this->_model;
}
}
}
4 changes: 2 additions & 2 deletions controllers/RecoveryController.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public function actionRecovery () {
$form2->attributes=$_POST['UserChangePassword'];
if($form2->validate()) {
$find->password = Yii::app()->controller->module->encrypting($form2->password);
$find->activkey=Yii::app()->controller->module->encrypting(microtime().$form2->password);
$find->activkey=md5(microtime().$form2->password);
if ($find->status==0) {
$find->status = 1;
}
Expand Down Expand Up @@ -64,4 +64,4 @@ public function actionRecovery () {
}
}

}
}
6 changes: 3 additions & 3 deletions controllers/RegistrationController.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,9 @@ public function actionRegistration() {
if($model->validate()&&$profile->validate())
{
$soucePassword = $model->password;
$model->activkey=UserModule::encrypting(microtime().$model->password);
$model->activkey=md5(microtime().$model->password);
$model->password=UserModule::encrypting($model->password);
$model->verifyPassword=UserModule::encrypting($model->verifyPassword);
$model->verifyPassword=$model->password;
$model->superuser=0;
$model->status=((Yii::app()->controller->module->activeAfterRegister)?User::STATUS_ACTIVE:User::STATUS_NOACTIVE);

Expand Down Expand Up @@ -77,4 +77,4 @@ public function actionRegistration() {
$this->render('/user/registration',array('model'=>$model,'profile'=>$profile));
}
}
}
}
4 changes: 2 additions & 2 deletions migrations/m110805_153437_installYiiUser.php
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ public function safeUp()
"username" => $this->_model->username,
"password" => Yii::app()->getModule('user')->encrypting($this->_model->password),
"email" => "[email protected]",
"activkey" => Yii::app()->getModule('user')->encrypting(microtime()),
"activkey" => md5(microtime()),
"createtime" => time(),
"lastvisit" => "0",
"superuser" => "1",
Expand Down Expand Up @@ -209,4 +209,4 @@ private function readStdinUser($prompt, $field, $default = '') {
}
return $input;
}
}
}
13 changes: 7 additions & 6 deletions models/UserChangePassword.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,10 @@ public function attributeLabels()
/**
* Verify Old Password
*/
public function verifyOldPassword($attribute, $params)
{
if (User::model()->notsafe()->findByPk(Yii::app()->user->id)->password != Yii::app()->getModule('user')->encrypting($this->$attribute))
$this->addError($attribute, UserModule::t("Old Password is incorrect."));
}
}
public function verifyOldPassword($attribute, $params)
{
$user = User::model()->notsafe()->findByPk(Yii::app()->user->id);
if (!Yii::app()->getModule('user')->verifyPassword($this->$attribute, $user->password))
$this->addError($attribute, UserModule::t("Old Password is incorrect."));
}
}