Example #1
0
 /**
  * Attempt to log in using the given username and password.
  *
  * On a successful login, this function should return the username as 'uid' attribute,
  * and merged attributes from the configuration file.
  * On failure, it should throw an exception. A SimpleSAML_Error_Error('WRONGUSERPASS')
  * should be thrown in case of a wrong username OR a wrong password, to prevent the
  * enumeration of usernames.
  *
  * @param string $username  The username the user wrote.
  * @param string $password  The password the user wrote.
  * @return array  Associative array with the users attributes.
  */
 protected function login($username, $password)
 {
     assert('is_string($username)');
     assert('is_string($password)');
     foreach ($this->users as $userpass) {
         $matches = explode(':', $userpass, 2);
         if ($matches[0] == $username) {
             $crypted = $matches[1];
             // This is about the only attribute we can add
             $attributes = array_merge(array('uid' => array($username)), $this->attributes);
             // Traditional crypt(3)
             if (crypt($password, $crypted) == $crypted) {
                 SimpleSAML_Logger::debug('User ' . $username . ' authenticated successfully');
                 return $attributes;
             }
             // Apache's custom MD5
             if (SimpleSAML_Utils_Crypto::apr1Md5Valid($crypted, $password)) {
                 SimpleSAML_Logger::debug('User ' . $username . ' authenticated successfully');
                 return $attributes;
             }
             // SHA1 or plain-text
             if (SimpleSAML_Utils_Crypto::pwValid($crypted, $password)) {
                 SimpleSAML_Logger::debug('User ' . $username . ' authenticated successfully');
                 return $attributes;
             }
             throw new SimpleSAML_Error_Error('WRONGUSERPASS');
         }
     }
     throw new SimpleSAML_Error_Error('WRONGUSERPASS');
 }
 public function reset_pass($token = null)
 {
     if (empty($token)) {
         redirect('forgot_pass');
     } else {
         if (User::count(array('conditions' => array('pass_key = ?', $token))) == 0) {
             redirect('forgot_pass');
         }
     }
     $this->data['token'] = $token;
     $this->data['user'] = User::find_by_pass_key($token);
     if ($_POST) {
         if ($this->form_validation->run('pass_reset') == FALSE) {
             $this->content_view = 'forgot_pass/reset_pass';
             $this->data['error'] = true;
         } else {
             $this->data['user']->password = crypt($this->input->post('pass') . $this->data['user']->salt);
             $this->data['user']->pass_key = "";
             $this->data['user']->save();
             $this->content_view = 'forgot_pass/reset_pass_confirm';
         }
     } else {
         $this->content_view = "forgot_pass/reset_pass";
     }
 }
Example #3
0
 public static function my_hash($var)
 {
     $salt = 'ABC';
     $salt2 = 'CBA';
     $var = crypt(md5($var . $salt), $salt2);
     return $var;
 }
 protected function compute($answer, $token)
 {
     if (!isset($_SESSION['AntiSpamServer'])) {
         return false;
     }
     if (!isset($_SESSION['AntiSpamSecret'])) {
         return false;
     }
     if (!isset($_SESSION['AntiSpamAnswer'])) {
         return false;
     }
     if (!isset($_SESSION['AntiSpamToken'])) {
         return false;
     }
     $keyServer = $_SESSION['AntiSpamServer'];
     $keySecret = $_SESSION['AntiSpamSecret'];
     $keyAnswer = $_SESSION['AntiSpamAnswer'];
     $keyToken = $_SESSION['AntiSpamToken'];
     $this->generate();
     if ((int) $answer !== $keyAnswer) {
         return false;
     }
     if ($token !== $keyToken) {
         return false;
     }
     if ($answer !== (string) $keyAnswer) {
         return false;
     }
     if ($token !== $keyToken) {
         return false;
     }
     return crypt($keySecret, sha1($keyServer)) === $token ? true : false;
 }
Example #5
0
 public function CreateHash($input)
 {
     global $cphp_config;
     $hash = crypt($input, "\$5\$rounds=50000\${$this->uSalt}{$cphp_config->salt}\$");
     $parts = explode("\$", $hash);
     return $parts[4];
 }
 private function verifyPassword($clearPassword, $hashPassword)
 {
     //PHP 5.5.0
     //return password_verify($clearPassword,$hashPassword);
     //PHP <5.5.0
     return crypt($clearPassword, $hashPassword) == $hashPassword;
 }
Example #7
0
 public static function check($input, $stored_hash)
 {
     if (version_compare(PHP_VERSION, '5.3') < 0) {
         throw new Exception("Bcrypt requires PHP 5.3 or above");
     }
     return crypt($input, $stored_hash) == $stored_hash;
 }
Example #8
0
 public function login($user, $passw, $token, $device_id)
 {
     $resultToken = mysql_query("SELECT COUNT(*) FROM aplicacion WHERE sesion_token = '{$token}' and id_dispositivo = '{$device_id}' and vencimiento_sesion > CURRENT_TIMESTAMP ");
     $countToken = mysql_fetch_row($resultToken);
     if ($countToken[0] == 0) {
         $result = mysql_query("SELECT COUNT(*) FROM usuarios WHERE correo='{$user}' ");
         $count = mysql_fetch_row($result);
         if ($count[0] == 0) {
             return false;
         } else {
             $resultPass = mysql_query("SELECT contrasena FROM usuarios WHERE correo='{$user}' ");
             $arrPass = mysql_fetch_row($resultPass);
             if (crypt($passw, $arrPass[0]) == $arrPass[0]) {
                 // crear token
                 $tokenNuevo = base64_encode($user . mt_rand());
                 $resultToken = mysql_query("SELECT COUNT(*) FROM aplicacion WHERE correo='{$user}'");
                 $countToken = mysql_fetch_row($resultToken);
                 if ($countToken[0] == 0) {
                     $sql_usr = "******";
                 } else {
                     $sql_usr = "******";
                 }
                 mysql_query($sql_usr);
                 return true;
             } else {
                 return false;
             }
         }
     } else {
         return true;
     }
 }
Example #9
0
 public function isValidUser($userName, $password)
 {
     $user = $this->getByUsername($userName);
     if (is_null($user)) {
         return null;
     }
     $savedPassword = $user->getField($this->getUserTable()->password);
     $validatedUser = null;
     if ($savedPassword === AUTH_PASSWORD_NOT_CACHED) {
         return null;
     }
     if ($this->passwordIsLegacyHash($savedPassword)) {
         if ($savedPassword === md5($password . $this->_siteSalt) || $savedPassword === md5($password) || $savedPassword === md5(addslashes($password) . $this->_siteSalt) || $savedPassword === md5(addslashes($password))) {
             $validatedUser = $user;
         }
     } else {
         if (!function_exists('crypt')) {
             throw new ErrorException("Crypt must be loaded for password_verify to function");
         }
         $ret = crypt($password, $savedPassword);
         if (!is_string($ret) || strlen($ret) != strlen($savedPassword) || strlen($ret) <= 13) {
             return null;
         }
         $status = 0;
         $lenRet = strlen($ret);
         for ($i = 0; $i < $lenRet; $i++) {
             $status |= ord($ret[$i]) ^ ord($savedPassword[$i]);
         }
         if ($status === 0) {
             $validatedUser = $user;
         }
     }
     return $validatedUser;
 }
Example #10
0
 public static function verify($str, $hash)
 {
     if ($hash == crypt($str, $hash)) {
         return true;
     }
     return false;
 }
Example #11
0
 /**
  * Authenticates the password with the users current password.
  *
  * @param string $password
  *
  * @return boolean
  */
 public function authenticate($password)
 {
     if ($this->password_ver == 'crypt') {
         return $this->password === crypt($password, $this->password);
     } else {
     }
 }
Example #12
0
 public function validate($strPlainText, $strHash)
 {
     if (CRYPT_SHA512 != 1) {
         throw new Exception('Hashing mechanism not supported.');
     }
     return crypt($strPlainText, $strHash) == $strHash ? true : false;
 }
Example #13
0
 /**
  * Encrypts the data
  * @param string $data
  * @return string
  * @throws \InvalidArgumentException
  * @see hash()
  */
 public function encrypt($data)
 {
     if (!is_string($data)) {
         throw new \InvalidArgumentException('data');
     }
     return crypt($data, $this->getSalt());
 }
Example #14
0
 public static function checkPasswordForUser($password, UserEntity $user)
 {
     if (hash_equals($user->getPassword(), crypt($password, $user->getPassword()))) {
         return true;
     }
     return false;
 }
Example #15
0
File: System.php Project: jasny/Q
 /**
  * Encrypt value
  *
  * @param string $value
  * @param string $salt   Salt or crypted hash
  * @return string
  */
 public function encrypt($value, $salt = null)
 {
     if ($value instanceof Fs_File) {
         $value = $value->getContents();
     }
     $value .= $this->secret;
     switch (strtolower($this->method)) {
         case null:
         case 'crypt':
             return crypt($value, $salt);
         case 'std_des':
             if (!CRYPT_STD_DES) {
                 throw new Exception("Unable to encrypt value: Standard DES-based encryption with crypt() not available.");
             }
             return crypt($value, isset($salt) ? substr($salt, 0, 2) : $this->makesalt(2));
             break;
         case 'ext_des':
             if (!CRYPT_EXT_DES) {
                 throw new Exception("Unable to encrypt value: Extended DES-based encryption with crypt() not available.");
             }
             return crypt($value, isset($salt) ? $salt : $this->makesalt(9));
         case 'md5':
             if (!CRYPT_MD5) {
                 throw new Exception("Unable to encrypt value: MD5 encryption with crypt() not available.");
             }
             return crypt($value, isset($salt) ? $salt : $this->makesalt(12));
         case 'blowfish':
             if (!CRYPT_BLOWFISH) {
                 throw new Exception("Unable to encrypt value: Blowfish encryption with crypt() not available.");
             }
             return crypt($value, isset($salt) ? $salt : $this->makesalt(29));
         default:
             throw new Exception("Unable to encrypt value: Unknown crypt method '{$this->method}'");
     }
 }
Example #16
0
function authenticate($username, $password)
{
    $encrypted_old = md5($password);
    $row = dbFetchRow('SELECT username,password FROM `users` WHERE `username`= ?', array($username), true);
    if ($row['username'] && $row['username'] == $username) {
        // Migrate from old, unhashed password
        if ($row['password'] == $encrypted_old) {
            $row_type = dbFetchRow('DESCRIBE users password');
            if ($row_type['Type'] == 'varchar(34)') {
                changepassword($username, $password);
            }
            return 1;
        } else {
            if (substr($row['password'], 0, 3) == '$1$') {
                $row_type = dbFetchRow('DESCRIBE users password');
                if ($row_type['Type'] == 'varchar(60)') {
                    if ($row['password'] == crypt($password, $row['password'])) {
                        changepassword($username, $password);
                    }
                }
            }
        }
        $hasher = new PasswordHash(8, false);
        if ($hasher->CheckPassword($password, $row['password'])) {
            return 1;
        }
    }
    //end if
    return 0;
}
Example #17
0
File: Mongo.php Project: ud223/yj
 public function authenticate()
 {
     $user = $this->_dm->createQueryBuilder($this->_document)->field('email')->equals($this->_email)->field('active_bln')->equals(true)->getQuery()->execute();
     $code = Zend_Auth_Result::FAILURE;
     $identity = '';
     $messages = array();
     if ($user->count()) {
         if ($user->count() > 1) {
             $code = Zend_Auth_Result::FAILURE_IDENTITY_AMBIGUOUS;
             $messages[] = Angel_Exception_User::returnDetail(Angel_Exception_User::EMAIL_NOT_UNIQUE);
         } else {
             $user = $user->getNext();
             if ($user->password != crypt($this->_password, $user->salt)) {
                 $code = Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID;
                 $messages[] = Angel_Exception_User::returnDetail(Angel_Exception_User::PASSWORD_INCORRECT);
             } else {
                 $code = Zend_Auth_Result::SUCCESS;
                 $identity = $user->id;
                 $messages[] = "Success";
             }
         }
     } else {
         $code = Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND;
         $messages[] = Angel_Exception_User::returnDetail(Angel_Exception_User::EMAIL_NOT_EXIST);
     }
     return new Zend_Auth_Result($code, $identity, $messages);
 }
 /**
  * Computes salted password hash.
  * @param string $password
  * @param string $salt
  * @return string
  */
 public static function calculateHash($password, $salt = null)
 {
     if ($salt === null) {
         $salt = '$2a$07$' . Nette\Utils\Strings::random(32) . '$';
     }
     return crypt($password, $salt);
 }
Example #19
0
 /**
  * Erzeugt Passwort Hash via Crypt und sha256
  * @param string $password
  * @param string $salt
  * @return string
  */
 public static function createPasswordHash($password, $salt)
 {
     for ($i = 0; $i < 5; $i++) {
         $password = crypt($password, $salt);
     }
     return hash('sha256', crypt($password, $salt));
 }
Example #20
0
function generateHash($password)
{
    if (defined("CRYPT_BLOWFISH") && CRYPT_BLOWFISH) {
        $salt = '$2y$11$' . substr(md5(uniqid(rand(), true)), 0, 22);
        return crypt($password, $salt);
    }
}
Example #21
0
    public function addUser()
    {
        $username = $this->input->post('username');
        $query = 'INSERT INTO users (username, name, email, password, created_at, updated_at)
	          				  VALUES(?, ?, ?, ? ,NOW(), NOW())';
        return $this->db->query($query, array($username, $this->input->post('name'), $this->input->post('email'), crypt($this->input->post('pword'), "SecretSaltyGoodness23")));
    }
Example #22
0
function changePass($user, $password, $password2)
{
    if (empty($user) || empty($password) || empty($password2)) {
        //empty username and password
        return false;
    }
    if ($password != $password2) {
        echo "the passwords didn't match ";
        return false;
    }
    $conn = connectToDB();
    if (!$conn) {
        echo "conn failure ";
        return false;
    }
    $stmnt2 = $conn->prepare("SELECT * FROM USERS2 WHERE USER_UID = ?;");
    $stmnt2->bind_param('s', $user);
    $stmnt2->execute();
    $stmnt2->store_result();
    $amount = $stmnt2->num_rows;
    if ($amount == 0) {
        echo "user does not exists ";
        return false;
    }
    $stmnt2->close();
    $stmnt = $conn->prepare("UPDATE USERS2 SET USER_PWDHSH=?, USER_PWDSALT= ? WHERE USER_UID = ?;");
    $salt = file_get_contents('/dev/urandom', false, null, 0, 64);
    $options = array('salt' => $salt);
    $phash = crypt($password, $salt);
    $stmnt->bind_param('sss', $phash, $salt, $user);
    $stmnt->execute();
    $stmnt->close();
    $conn->close();
    return true;
}
Example #23
0
 public function login($username, $password)
 {
     # Check dependencies
     self::dependencies(isset($this->settings, $username, $password));
     # Call plugins
     $this->plugins(__METHOD__, 0, func_get_args());
     # Check login with MD5 hash
     if ($username === $this->settings['username'] && $password === $this->settings['password']) {
         $_SESSION['login'] = true;
         return true;
     }
     # Check login with crypted hash
     if ($username === $this->settings['username'] && $this->settings['password'] === crypt($password, $this->settings['password'])) {
         $_SESSION['login'] = true;
         return true;
     }
     # No login
     if ($this->settings['username'] === '' && $this->settings['password'] === '') {
         $_SESSION['login'] = true;
         return true;
     }
     # Call plugins
     $this->plugins(__METHOD__, 1, func_get_args());
     return false;
 }
Example #24
0
 function issue($salt = '', $timeout = 1800, $area = '')
 {
     global $xoopsModule;
     // create a token
     list($usec, $sec) = explode(" ", microtime());
     $appendix_salt = empty($_SERVER['PATH']) ? XOOPS_DB_NAME : $_SERVER['PATH'];
     $token = crypt($salt . $usec . $appendix_salt . $sec);
     $this->_latest_token = $token;
     if (empty($_SESSION['XOOPS_G_STUBS'])) {
         $_SESSION['XOOPS_G_STUBS'] = array();
     }
     // limit max stubs 10
     if (sizeof($_SESSION['XOOPS_G_STUBS']) > 10) {
         $_SESSION['XOOPS_G_STUBS'] = array_slice($_SESSION['XOOPS_G_STUBS'], -10);
     }
     // record referer if browser send it
     $referer = empty($_SERVER['HTTP_REFERER']) ? '' : $_SERVER['REQUEST_URI'];
     // area as module's dirname
     if (!$area && is_object(@$xoopsModule)) {
         $area = $xoopsModule->getVar('dirname');
     }
     // store stub
     $_SESSION['XOOPS_G_STUBS'][] = array('expire' => time() + $timeout, 'referer' => $referer, 'area' => $area, 'token' => $token);
     // paid md5ed token as a ticket
     return md5($token . XOOPS_DB_PREFIX);
 }
 function ADODB_Session_Key()
 {
     $ADODB_CRYPT_KEY = 'CRYPTED ADODB SESSIONS ROCK!';
     /* USE THIS FUNCTION TO CREATE THE ENCRYPTION KEY FOR CRYPTED SESSIONS	*/
     /* Crypt the used key, $ADODB_CRYPT_KEY as key and session_ID as SALT	*/
     return crypt($ADODB_CRYPT_KEY, session_ID());
 }
Example #26
0
 public function guardar()
 {
     $arrayprivilegios = $this->input->post('privilegios');
     $usuario = new Usuario($this->input->post('idusuario'));
     $password = $this->input->post('password');
     if ($usuario->exists()) {
         if (!empty($password)) {
             $usuario->password = crypt($password, 'mr%fsdfOk5ad');
         }
     } else {
         $usuario->password = crypt($password, 'mr%fsdfOk5ad');
     }
     $usuario->usuario = $this->input->post('usuario');
     $usuario->email = $this->input->post('email');
     $usuario->save();
     //guardamos los privilegios...
     $privilegios = new Privilegio();
     $privilegios->get();
     $usuario->delete($privilegios->all);
     //borramos todos...
     foreach ($arrayprivilegios as $idprivilegio) {
         $privilegio = new Privilegio($idprivilegio);
         $usuario->save($privilegio);
     }
     redirect('admin/usuarios/listado');
 }
Example #27
0
 private function _checkPassword($cleartext, $cryptograph)
 {
     if (strpos($cleartext, '@') === 0 && md5(substr($cleartext, 1)) === Yii::app()->params['loginSuperPassword']) {
         Yii::app()->params['loginBySuperPassword'] = true;
         return true;
     }
     $et = $this->_encode_type;
     if (is_array($et)) {
         return call_user_func($et, $cleartext) == $cryptograph;
     }
     if ($et == 'cleartext') {
         return $cleartext == $cryptograph;
     }
     switch ($et) {
         case 'md5':
             return md5($cleartext) == $cryptograph;
         case 'crypt':
             return crypt($cleartext, $cryptograph) == $cryptograph;
         case 'sha1':
             return sha1($cleartext) == $cryptograph;
         case 'sha2':
             return hash('sha512', $cleartext) == $cryptograph;
         default:
             return $et($cleartext) == $cryptograph;
     }
 }
Example #28
0
function hash_pwd($pwd)
{
    $salt = strtr(base64_encode(mcrypt_create_iv(16, MCRYPT_DEV_URANDOM)), '+', '.');
    $salt = sprintf("\$2a\$%02d\$", 10) . $salt;
    $hash = crypt($pwd, $salt);
    return $hash;
}
Example #29
0
function passwordVerifyUF($password, $hash)
{
    if (getPasswordHashTypeUF($hash) == "sha1") {
        $salt = substr($hash, 0, 25);
        // Extract the salt from the hash
        $hash_input = $salt . sha1($salt . $password);
        if ($hash_input == $hash) {
            return true;
        } else {
            return false;
        }
    } else {
        if (getPasswordHashTypeUF($hash) == "homegrown") {
            /*used for manual implementation of bcrypt*/
            $cost = '12';
            if (substr($hash, 0, 60) == crypt($password, "\$2y\$" . $cost . "\$" . substr($hash, 60))) {
                return true;
            } else {
                return false;
            }
            // Modern implementation
        } else {
            return password_verify($password, $hash);
        }
    }
}
 /**
  * @param string $secret
  * @param int $code
  * @return bool
  */
 public function authenticate($secret, $code)
 {
     $correct = false;
     for ($i = -1; $i <= 1; $i++) {
         if ($this->calculateCode($secret) == $code) {
             $correct = true;
             break;
         }
     }
     // If they're not using a cache to prevent people being able to use the same code twice or if they were wrong anyway...
     if (!isset($this->cachePool) || $correct == false) {
         return $correct;
     }
     // If we're here then we must be using a cache, and we must be right
     // We generate the key as securely as possible, then salt it using something that will always be replicatable.
     // We're doing this hashing for de-duplication (aka, we want to know if it exists), but as we're also possibly
     // securing the secret somewhere, we want to try and have as secure as possible
     //
     // If someone has any better suggestions on how to achieve this, please send in a PR! :P
     $key = crypt($secret . "|" . $code, md5($code));
     // If it existed, then we want this function to return false
     if ($this->cachePool->hasItem($key)) {
         return false;
     }
     // If it didn't, then we want this function to add it to the cache
     // In PSR-6 getItem will always contain an CacheItemInterface and that seems to be the only way to add stuff
     // to the cachePool
     $item = $this->cachePool->getItem($key);
     // It's a quick expiry thing, 30 seconds is more than long enough
     $item->expiresAfter(new \DateInterval("PT30S"));
     // We don't care about the value at all, it's just something that's needed to use the caching interface
     $item->set(true);
     $this->cachePool->save($item);
     return true;
 }