Beispiel #1
0
function addUser($mysqli, $email, $pwd)
{
    $crypto = new Crypto();
    $salt = $crypto->generateSalt(10);
    $hash = $crypto->generateHash($pwd, $salt);
    $sql = "INSERT INTO users(email, hash, salt, nbrAttempts) \n\t\t\tVALUES('" . $email . "', '" . $hash . "', '" . $salt . "', '0')";
    $mysqli->multi_query($sql);
    $_SESSION['isLoggedIn'] = 1;
    $_SESSION['username'] = $email;
    redirect("https://127.0.0.1/searchView.php");
}
Beispiel #2
0
 public static function hmacSha1Verify($key, $in, $expected)
 {
     $hmac = Crypto::hmacSha1($key, $in);
     if ($hmac != $expected) {
         throw new GeneralSecurityException("HMAC verification failure");
     }
 }
Beispiel #3
0
 /**
  * {@inheritDoc}
  */
 public function unwrap($in, $maxAgeSec)
 {
     //TODO remove this once we have a better way to generate a fake token
     // in the example files
     if (Config::get('allow_plaintext_token') && count(explode(':', $in)) == 6) {
         $data = explode(":", $in);
         $out = array();
         $out['o'] = $data[0];
         $out['v'] = $data[1];
         $out['a'] = $data[2];
         $out['d'] = $data[3];
         $out['u'] = $data[4];
         $out['m'] = $data[5];
     } else {
         //TODO Exception handling like JAVA
         $bin = base64_decode($in);
         $cipherText = substr($bin, 0, strlen($bin) - Crypto::$HMAC_SHA1_LEN);
         $hmac = substr($bin, strlen($cipherText));
         Crypto::hmacSha1Verify($this->hmacKey, $cipherText, $hmac);
         $plain = Crypto::aes128cbcDecrypt($this->cipherKey, $cipherText);
         $out = $this->deserialize($plain);
         $this->checkTimestamp($out, $maxAgeSec);
     }
     return $out;
 }
 /**
  * @see BasicBlobCrypter::unwrap();
  */
 public function unwrap($in, $maxAgeSec)
 {
     if ($this->allowPlaintextToken && count(explode(':', $in)) == 7) {
         $data = explode(":", $in);
         $out = array();
         $out['o'] = $data[0];
         $out['v'] = $data[1];
         $out['a'] = $data[2];
         $out['d'] = $data[3];
         $out['u'] = $data[4];
         $out['m'] = $data[5];
     } else {
         $bin = base64_decode($in);
         if (is_callable('mb_substr')) {
             $cipherText = mb_substr($bin, 0, -Crypto::$HMAC_SHA1_LEN, 'latin1');
             $hmac = mb_substr($bin, mb_strlen($cipherText, 'latin1'), Crypto::$HMAC_SHA1_LEN, 'latin1');
         } else {
             $cipherText = substr($bin, 0, -Crypto::$HMAC_SHA1_LEN);
             $hmac = substr($bin, strlen($cipherText));
         }
         Crypto::hmacSha1Verify($this->hmacKey, $cipherText, $hmac);
         $plain = base64_decode($cipherText);
         if ($this->allowPlaintextToken) {
             $plain = base64_decode($cipherText);
         } else {
             $plain = opShindigCrypto::decrypt($this->cipherKey, $cipherText);
         }
         $out = $this->deserialize($plain);
         $this->checkTimestamp($out, $maxAgeSec);
     }
     return $out;
 }
 public function ConvertPaymentModules()
 {
     $this->Log('Convert payment modules');
     // Clear tables
     $this->TruncateTable('pmodules', 'pmodules_config');
     // Copy pmodules table
     $pmodule_rset = $this->DbOld->GetAll('SELECT * FROM pmodules');
     foreach ($pmodule_rset as &$row) {
         if ($row['name'] == 'offline_payment') {
             $row['name'] = 'OfflineBank';
         }
     }
     $this->BulkInsert('pmodules', $pmodule_rset);
     // For each pmodule copy config settings
     $pmodule_config = array();
     $Crypto = $GLOBALS['Crypto'];
     foreach ($pmodule_rset as $pmodule) {
         // Get old config form for current pmodule
         $rset = $this->DbOld->GetAll('SELECT * FROM pmodules_config WHERE module_name = ?', array($pmodule['name']));
         foreach ($rset as $row) {
             // Encrypt config value
             $row['value'] = $this->Crypto->Encrypt($row['key'], LICENSE_FLAGS::REGISTERED_TO);
             // Push it to pmodule config
             $pmodule_config[] = $row;
         }
     }
     $this->BulkInsert('pmodules_config', $pmodule_config);
 }
Beispiel #6
0
 public static function decrypt($string, $key = null, $salt = null, $iv = null)
 {
     $config = ConfigManager::getConfig('Crypto', 'AES256')->AuxConfig;
     if ($key === null) {
         $key = $config->key;
     }
     if ($salt === null) {
         $salt = $config->salt;
     }
     if ($iv === null) {
         $iv = $config->iv;
     }
     $td = mcrypt_module_open('rijndael-128', '', MCRYPT_MODE_CBC, '');
     $ks = mcrypt_enc_get_key_size($td);
     $bs = mcrypt_enc_get_block_size($td);
     $iv = substr(hash("sha256", $iv), 0, $bs);
     // Create key
     $key = Crypto::pbkdf2("sha512", $key, $salt, $config->pbkdfRounds, $ks);
     // Initialize encryption module for decryption
     mcrypt_generic_init($td, $key, $iv);
     $decryptedString = "";
     // Decrypt encrypted string
     try {
         if (ctype_xdigit($string)) {
             $decryptedString = trim(mdecrypt_generic($td, pack("H*", $string)));
         }
     } catch (ErrorException $e) {
     }
     // Terminate decryption handle and close module
     mcrypt_generic_deinit($td);
     mcrypt_module_close($td);
     // Show string
     return $decryptedString;
 }
 public function isAuthenticated($request)
 {
     $currentTime = time();
     if (isset($request[$this->cookieName])) {
         $connection = $request[$this->cookieName]['CON'];
         $timestamp = $request[$this->cookieName]['TM'];
         if ($connection && $timestamp) {
             if ($currentTime - $timestamp < $this->cookieExpireTime) {
                 $temp = Crypto::decrypt($connection, _Key_New);
                 list($username) = explode("|Z|1|Z|", $temp);
                 if ($username) {
                     $connection = Crypto::encrypt(implode("|Z|1|Z|", array($username, time())), _Key_New);
                     $this->setAuthenticated($connection);
                     return true;
                 }
             } else {
                 // Timed-out
                 return false;
             }
         } else {
             // Not Authenticated
             return false;
         }
     }
 }
Beispiel #8
0
 function testRandom()
 {
     for ($i = 1; $i < 128; $i += 4) {
         $data = Crypto::random($i);
         $this->assertNotEqual($data, '', 'Empty random data generated');
         $this->assert(strlen($data) == $i, 'Random data received was not the length requested');
     }
 }
Beispiel #9
0
 /**
  * @param $email
  * @param $password
  * @param $name
  * @param $host
  * @param $port
  * @param string|null $encryptionProtocol
  * @param $user
  * @return MailAccount
  */
 public function connect($email, $password, $name, $host, $port, $encryptionProtocol, $user)
 {
     $account = new MailAccount();
     $account->setUserId($this->userId);
     $account->setName($name);
     $account->setEmail($email);
     $account->setInboundHost($host);
     $account->setInboundPort($port);
     $account->setInboundSslMode($encryptionProtocol);
     $account->setInboundUser($user);
     $password = $this->crypto->encrypt($password);
     $account->setInboundPassword($password);
     $a = new Account($account);
     $a->getImapConnection();
     $this->logger->info("Test-Account-Successful: {$this->userId}, {$host}, {$port}, {$user}, {$encryptionProtocol}");
     return $account;
 }
Beispiel #10
0
function addUser($mysqli, $email, $pwd)
{
    $sql = "INSERT INTO users(email, hash, salt, nbrAttempts) VALUES(?, ?, ?, '0')";
    $stmt = $mysqli->prepare($sql);
    $crypto = new Crypto();
    $salt = $crypto->generateSalt(10);
    $hash = $crypto->generateHash($pwd, $salt);
    if ($stmt->bind_param('sss', $email, $hash, $salt)) {
        if ($stmt->execute()) {
            echo "executed";
            $_SESSION['isLoggedIn'] = 1;
            $_SESSION['username'] = $email;
            redirect("https://127.0.0.1/searchView.php");
            $stmt->free_result();
        }
    }
}
Beispiel #11
0
 public function writeLog($message, $mode = 'all')
 {
     $time = date("F j, Y, g:i a");
     $ip = $_SERVER['REMOTE_ADDR'];
     $message = basename($_SERVER['SCRIPT_FILENAME']) . " [{$ip}] ({$time}) : " . $message;
     $msg = base64_encode(base64_encode(Crypto::EncryptString(base64_decode(base64_decode(ADMIN_KEY)), base64_decode(base64_decode(ADMIN_IV)), $message)));
     DbManager::i()->insert("sf_logs", array("message", "mode"), array($msg, $mode));
 }
 public function createWalletUser($username, $password, $email, $token)
 {
     $walletClient = new Client(null, null, $this->walletApiUrl);
     $keys = $this->getUserKeys($username, $password, array('wallet', 'api', 'key'));
     $account = array('token' => $token, 'username' => $username, 'email' => $email, 'country' => '', 'timezone' => '', 'keys' => array('wallet' => $keys['wallet']['private'], 'api' => Crypto::signData($keys['api']['private']), 'key' => Crypto::signData($keys['key']['private'])));
     $result = $walletClient->query('user/create', 'POST', $account, false);
     return $result;
 }
 /**
  * Configura o schema do model corrente
  *
  * @return 	void
  */
 public function setSchema()
 {
     $esquema = Cache::read('Esquema.' . $this->name);
     if (!isset($esquema) || empty($esquema)) {
         $meuEsquema = isset($this->esquema) ? $this->esquema : array();
         $this->esquema = array();
         $this->schema();
         foreach ($this->_schema as $_field => $_arrProp) {
             $this->esquema[$_field] = isset($meuEsquema[$_field]) ? $meuEsquema[$_field] : array();
             $this->esquema[$_field]['alias'] = isset($meuEsquema[$_field]['alias']) ? $meuEsquema[$_field]['alias'] : Crypto::word($_field);
             $this->esquema[$_field]['type'] = isset($meuEsquema[$_field]['type']) ? $meuEsquema[$_field]['type'] : $_arrProp['type'];
             if (isset($_arrProp['key'])) {
                 $this->esquema[$_field]['key'] = $_arrProp['key'];
             }
             if (isset($_arrProp['key'])) {
                 $this->esquema[$_field]['sort'] = true;
             }
             $input = isset($meuEsquema[$_field]['input']) ? $meuEsquema[$_field]['input'] : array();
             $input['label'] = isset($meuEsquema[$_field]['input']['label']) ? $meuEsquema[$_field]['input']['label'] : ucfirst(Inflector::camelize($_field));
             $input['type'] = isset($meuEsquema[$_field]['input']['type']) ? $meuEsquema[$_field]['input']['type'] : 'text';
             $input['div'] = isset($meuEsquema[$_field]['input']['div']) ? $meuEsquema[$_field]['input']['div'] : 'div' . Crypto::word(Inflector::camelize($this->name . '_' . $_field)) . ' div' . Crypto::word(Inflector::camelize($_field));
             if (isset($_arrProp['default'])) {
                 $input['default'] = $_arrProp['default'];
             }
             if (isset($_arrProp['null']) && $_arrProp['null'] === false) {
                 $input['required'] = 'required';
             }
             if (isset($_arrProp['length'])) {
                 $input['maxlength'] = $_arrProp['length'];
             }
             if (in_array($_field, array('criado', 'modificado'))) {
                 unset($input['required']);
                 $input['disabled'] = 'disabled';
             }
             if (in_array($_arrProp['type'], array('date', 'data', 'datetime')) && !isset($input['disabled'])) {
                 $input['class'] = isset($input['class']) ? $input['class'] : ' in-data';
             }
             if (in_array($_arrProp['type'], array('text'))) {
                 $input['type'] = 'textarea';
             }
             if (in_array($_arrProp['type'], array('decimal'))) {
                 $length = isset($_arrProp['length']) ? $_arrProp['length'] : null;
                 if (isset($length)) {
                     $input['maxlength'] = round($input['maxlength']) + round($input['maxlength']) / 3 - 1;
                     $length = substr($length, strpos($length, ',') + 1, strlen($length));
                     $this->esquema[$_field]['decimais'] = $length;
                 }
                 $input['class'] = isset($input['class']) ? $input['class'] : ' in-decimal';
             }
             $this->esquema[$_field]['input'] = $input;
         }
         if (USAR_CACHE === true) {
             Cache::write('Esquema.' . $this->name, $this->esquema);
         }
     } else {
         $this->esquema = $esquema;
     }
 }
 /**
  * This method is called before the first test of this test class is run.
  *
  * @return  void
  */
 public static function setUpBeforeClass()
 {
     // Only run the test if the environment supports it.
     try {
         Crypto::RuntimeTest();
     } catch (CryptoTestFailedException $e) {
         self::markTestSkipped('The environment cannot safely perform encryption with this cipher.');
     }
 }
Beispiel #15
0
 /**
  * Obtain a URL where we can redirect to securely post a form with the given data to a specific destination.
  *
  * @param string $destination The destination URL.
  * @param array  $data An associative array containing the data to be posted to $destination.
  *
  * @return string  A URL which allows to securely post a form to $destination.
  *
  * @author Jaime Perez, UNINETT AS <*****@*****.**>
  */
 private static function getSecurePOSTRedirectURL($destination, $data)
 {
     $session = \SimpleSAML_Session::getSessionFromRequest();
     $id = self::savePOSTData($session, $destination, $data);
     // encrypt the session ID and the random ID
     $info = base64_encode(Crypto::aesEncrypt($session->getSessionId() . ':' . $id));
     $url = \SimpleSAML_Module::getModuleURL('core/postredirect.php', array('RedirInfo' => $info));
     return preg_replace('#^https:#', 'http:', $url);
 }
 public static function decrypt($key, $text)
 {
     if (extension_loaded('mcrypt')) {
         return Crypto::aes128cbcDecrypt($key, $text);
     }
     $iv = substr($text, 0, 8);
     $encrypted = substr($text, 8, strlen($text));
     $blowfish = Crypt_Blowfish::factory('cbc', $key, $iv);
     return base64_decode($blowfish->decrypt($encrypted));
 }
Beispiel #17
0
 /**
  * Check if a user is logged in
  */
 public static function isLoggedIn()
 {
     if (empty($_COOKIE['s'])) {
         return false;
     } else {
         $str = Crypto::decrypt($_COOKIE['s'], $_SERVER['ENCRYPTION_KEY']);
         $fields = explode(':', $str);
         return $fields[1];
         // return the userid
     }
 }
Beispiel #18
0
 /**
  * Install the application
  */
 public function settings()
 {
     $form = new Form(array('id' => 'install-settings-form', 'labelWidth' => '30em', 'fieldsets' => array('global' => array('legend' => Lang::get('install.settings-global-legend', null, null, $this->language), new TextInput(array('name' => 'title', 'required' => true, 'label' => Lang::get('install.settings-title-label', null, null, $this->language), 'default' => DEFAULT_HTML_TITLE)), new TextInput(array('name' => 'rooturl', 'required' => true, 'label' => Lang::get('install.settings-rooturl-label', null, null, $this->language), 'placeholder' => 'http://', 'default' => getenv('REQUEST_SCHEME') . '://' . getenv('SERVER_NAME'))), new SelectInput(array('name' => 'timezone', 'required' => true, 'options' => array_combine(\DateTimeZone::listIdentifiers(), \DateTimeZone::listIdentifiers()), 'default' => DEFAULT_TIMEZONE, 'label' => Lang::get('install.settings-timezone-label')))), 'database' => array('legend' => Lang::get('install.settings-database-legend', null, null, $this->language), new TextInput(array('name' => 'db[host]', 'required' => true, 'label' => Lang::get('install.settings-db-host-label', null, null, $this->language), 'default' => 'localhost')), new TextInput(array('name' => 'db[username]', 'required' => true, 'label' => Lang::get('install.settings-db-username-label', null, null, $this->language))), new PasswordInput(array('name' => 'db[password]', 'required' => true, 'label' => Lang::get('install.settings-db-password-label', null, null, $this->language), 'pattern' => '/^.*$/')), new TextInput(array('name' => 'db[dbname]', 'required' => true, 'pattern' => '/^\\w+$/', 'label' => Lang::get('install.settings-db-dbname-label', null, null, $this->language))), new TextInput(array('name' => 'db[prefix]', 'default' => 'Hawk', 'pattern' => '/^\\w+$/', 'label' => Lang::get('install.settings-db-prefix-label', null, null, $this->language)))), 'admin' => array('legend' => Lang::get('install.settings-admin-legend', null, null, $this->language), new TextInput(array('name' => 'admin[login]', 'required' => true, 'pattern' => '/^\\w+$/', 'label' => Lang::get('install.settings-admin-login-label', null, null, $this->language))), new EmailInput(array('name' => 'admin[email]', 'required' => true, 'label' => Lang::get('install.settings-admin-email-label', null, null, $this->language))), new PasswordInput(array('name' => 'admin[password]', 'required' => true, 'label' => Lang::get('install.settings-admin-password-label', null, null, $this->language))), new PasswordInput(array('name' => 'admin[passagain]', 'required' => true, 'compare' => 'admin[password]', 'label' => Lang::get('install.settings-admin-passagain-label', null, null, $this->language)))), '_submits' => array(new SubmitInput(array('name' => 'valid', 'value' => Lang::get('install.install-button', null, null, $this->language), 'icon' => 'cog')))), 'onsuccess' => 'location.href = data.rooturl;'));
     if (!$form->submitted()) {
         // Display the form
         $body = View::make(Plugin::current()->getView('settings.tpl'), array('form' => $form));
         return \Hawk\Plugins\Main\MainController::getInstance()->index($body);
     } else {
         // Make the installation
         if ($form->check()) {
             /**
              * Generate Crypto constants
              */
             $salt = Crypto::generateKey(24);
             $key = Crypto::generateKey(32);
             $iv = Crypto::generateKey(16);
             $configMode = 'prod';
             /**
              * Create the database and it tables
              */
             $tmpfile = tempnam(sys_get_temp_dir(), '');
             DB::add('tmp', array(array('host' => $form->getData('db[host]'), 'username' => $form->getData('db[username]'), 'password' => $form->getData('db[password]'))));
             try {
                 DB::get('tmp');
             } catch (DBException $e) {
                 return $form->response(Form::STATUS_ERROR, Lang::get('install.install-connection-error'));
             }
             try {
                 $param = array('{{ $dbname }}' => $form->getData('db[dbname]'), '{{ $prefix }}' => $form->getData('db[prefix]'), '{{ $language }}' => $this->language, '{{ $timezone }}' => $form->getData('timezone'), '{{ $title }}' => Db::get('tmp')->quote($form->getData('title')), '{{ $email }}' => Db::get('tmp')->quote($form->getData('admin[email]')), '{{ $login }}' => Db::get('tmp')->quote($form->getData('admin[login]')), '{{ $password }}' => Db::get('tmp')->quote(Crypto::saltHash($form->getData('admin[password]'), $salt)), '{{ $ip }}' => Db::get('tmp')->quote(App::request()->clientIp()));
                 $sql = strtr(file_get_contents(Plugin::current()->getRootDir() . 'templates/install.sql.tpl'), $param);
                 // file_put_contents($tmpfile, $sql);
                 Db::get('tmp')->query($sql);
                 /**
                  * Create the config file
                  */
                 $param = array('{{ $salt }}' => addcslashes($salt, "'"), '{{ $key }}' => addcslashes($key, "'"), '{{ $iv }}' => addcslashes($iv, "'"), '{{ $configMode }}' => $configMode, '{{ $rooturl }}' => $form->getData('rooturl'), '{{ $host }}' => $form->getData('db[host]'), '{{ $username }}' => $form->getData('db[username]'), '{{ $password }}' => $form->getData('db[password]'), '{{ $dbname }}' => $form->getData('db[dbname]'), '{{ $prefix }}' => $form->getData('db[prefix]'), '{{ $sessionEngine }}' => $form->getData('session'), '{{ $version }}' => $form->getData('version'));
                 $config = strtr(file_get_contents(Plugin::current()->getRootDir() . 'templates/config.php.tpl'), $param);
                 file_put_contents(INCLUDES_DIR . 'config.php', $config);
                 /**
                  * Create etc/dev.php
                  */
                 App::fs()->copy(Plugin::current()->getRootDir() . 'templates/etc-dev.php', ETC_DIR . 'dev.php');
                 /**
                  * Create etc/prod.php
                  */
                 App::fs()->copy(Plugin::current()->getRootDir() . 'templates/etc-prod.php', ETC_DIR . 'prod.php');
                 $form->addReturn('rooturl', $form->getData('rooturl'));
                 return $form->response(Form::STATUS_SUCCESS, Lang::get('install.install-success'));
             } catch (\Exception $e) {
                 return $form->response(Form::STATUS_ERROR, Lang::get('install.install-error'));
             }
         }
     }
 }
Beispiel #19
0
 function getToken()
 {
     if (!$this->csrf['token'] || $this->isExpired()) {
         $this->csrf['token'] = sha1(session_id() . Crypto::random(16) . SECRET_SALT);
         $this->csrf['time'] = time();
     } else {
         //Reset the timer
         $this->csrf['time'] = time();
     }
     return $this->csrf['token'];
 }
 /**
  * Tests Crypto::hmacSha1Verify()
  */
 public function testHmacSha1Verify()
 {
     $string = 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit';
     $key = 'Aliquam erat volutpat';
     $expected = '%16%E7%E0E%22%08%5C%2B48%85d%FE%DE%C7%3A%C3%0D%11c';
     try {
         Crypto::hmacSha1Verify($key, $string, urldecode($expected));
         $success = true;
     } catch (GeneralSecurityException $e) {
         $success = false;
     }
     $this->assertTrue($success);
 }
Beispiel #21
0
 protected function __construct()
 {
     $encrypt = \Config::getConfig()->get('encrypt', FALSE);
     if ($encrypt) {
         $this->crypto = Crypto::getInstance();
     }
     $config = \Config::factory(\Config::getConfig()->get('cookie', array()), FALSE, 'cookie');
     $this->expire = $config->get('expire', 0);
     $this->path = $config->get('path', '/');
     $this->domain = $config->get('domain', '');
     $this->secure = $config->get('secure', FALSE);
     $this->httponly = $config->get('httponly', FALSE);
 }
Beispiel #22
0
 /**
  * Decrypt then verify a password
  * 
  * @param string $password          - The user-provided password
  * @param string $stored            - The encrypted password hash
  * @param EncryptionKey $secret_key  - The master key for all passwords
  * @return boolean
  */
 public static function verify(string $password, string $stored, EncryptionKey $secret_key) : bool
 {
     // First let's decrypt the hash
     $hash_str = Crypto::decrypt($stored, $secret_key);
     // Upon successful decryption, verify the password is correct
     $isArgon2 = \hash_equals(CryptoUtil::safeSubstr($hash_str, 0, 9), \Sodium\CRYPTO_PWHASH_STRPREFIX);
     $isScrypt = \hash_equals(CryptoUtil::safeSubstr($hash_str, 0, 3), \Sodium\CRYPTO_PWHASH_SCRYPTSALSA208SHA256_STRPREFIX);
     if ($isArgon2) {
         return \Sodium\crypto_pwhash_str_verify($hash_str, $password);
     } elseif ($isScrypt) {
         return \Sodium\crypto_pwhash_scryptsalsa208sha256_str_verify($hash_str, $password);
     }
     return false;
 }
 function run()
 {
     $sql = 'SELECT email_id, userpass, userid FROM ' . EMAIL_TABLE . " WHERE userpass <> ''";
     if (($res = db_query($sql)) && db_num_rows($res)) {
         while (list($id, $passwd, $username) = db_fetch_row($res)) {
             if (!$passwd) {
                 continue;
             }
             $ciphertext = Crypto::encrypt(self::_decrypt($passwd, SECRET_SALT), SECRET_SALT, $username);
             $sql = 'UPDATE ' . EMAIL_TABLE . ' SET userpass='******' WHERE email_id=' . db_input($id);
             db_query($sql);
         }
     }
 }
Beispiel #24
0
 public function KeyGet($master, $password, $key)
 {
     if ($this->MasterExists($master)) {
         require_once APP_DIR . "/src/Inc/Crypto.php";
         $items = getData("master_" . $master . "_items");
         $pass_salt = getData("master_" . $master . "_password_salt");
         $encrypt_key = $this->master_salt . $password . $pass_salt;
         Crypto::$KEY_BYTE_SIZE = mb_strlen($encrypt_key, '8bit');
         $items = base64_decode(Crypto::decrypt(base64_decode($items), $encrypt_key));
         $items = str_replace("&quot;", "'", $items);
         $items = $items == null ? array() : json_decode($items, true);
         return isset($items[$key]) ? $items[$key] : null;
     } else {
         return false;
     }
 }
 function __construct()
 {
     $settings = DbManager::i()->select("sf_settings", array("settings"));
     if ($settings !== false && !is_array($settings)) {
         $prefs = Crypto::DecryptString(base64_decode(base64_decode(ADMIN_KEY)), base64_decode(base64_decode(ADMIN_IV)), base64_decode(base64_decode($settings->settings)));
         $prefs = (array) json_decode(base64_decode($prefs));
         if (isset($prefs['cms_settings'])) {
             $settings = (array) $prefs['cms_settings'];
             if (isset($settings['title']) && strlen($settings['title']) > 0) {
                 $this->title = stripslashes(filter_var(htmlspecialchars($settings['title'])));
             }
             if (isset($settings['captcha_public']) && strlen($settings['captcha_public']) > 0) {
                 $this->captcha_public = stripslashes(filter_var(htmlspecialchars($settings['captcha_public'])));
             }
             if (isset($settings['captcha_secret']) && strlen($settings['captcha_private']) > 0) {
                 $this->captcha_private = stripslashes(filter_var(htmlspecialchars($settings['captcha_private'])));
             }
         }
         if (isset($prefs['paypal'])) {
             $settings = (array) $prefs['paypal'];
             if (isset($settings['username']) && strlen($settings['username']) > 0) {
                 $this->paypal_email = stripslashes(filter_var(htmlspecialchars($settings['username'])));
             }
             if (isset($settings['password']) && strlen($settings['password']) > 0) {
                 $this->paypal_api_pass = stripslashes(filter_var(htmlspecialchars($settings['password'])));
             }
             if (isset($settings['signature']) && strlen($settings['signature']) > 0) {
                 $this->paypal_api_signature = stripslashes(filter_var(htmlspecialchars($settings['signature'])));
             }
         }
         if (isset($prefs['btc'])) {
             $settings = (array) $prefs['btc'];
             if (isset($settings['api_key']) && strlen($settings['api_key']) > 0) {
                 $this->btc_api_key = stripslashes(filter_var(htmlspecialchars($settings['api_key'])));
             }
             if (isset($settings['api_pin']) && strlen($settings['api_pin']) > 0) {
                 $this->btc_api_pin = stripslashes(filter_var(htmlspecialchars($settings['api_pin'])));
             }
         }
         unset($prefs);
     }
 }
function renewPassword($c)
{
    $plain = Crypto::generateRandomPassword(15);
    $info = DbManager::i()->select("sf_members", array("key", "iv"), array("userid" => intval($c)));
    if ($info !== false && !is_array($info)) {
        $key = base64_decode(base64_decode($info->key));
        $iv = base64_decode(base64_decode($info->iv));
        $password = base64_encode(base64_encode(Crypto::EncryptString($key, $iv, $plain)));
        if (DbManager::i()->update("sf_members", array("password" => $password), array("userid" => intval($c)))) {
            unset($password);
            unset($key);
            unset($iv);
            unset($info);
            Logger::i()->writeLog("Password renewed for UserID: {$c}, password = {$plain}");
            return Submission::createResult($plain, true);
        }
    }
    Logger::i()->writeLog("Renew password failed, error = " . DbManager::i()->error, 'dev');
    return Submission::createResult("Could not renew password");
}
Beispiel #27
0
 function randCode($len = 8, $chars = false)
 {
     $chars = $chars ?: 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890_=';
     // Determine the number of bits we need
     $char_count = strlen($chars);
     $bits_per_char = ceil(log($char_count, 2));
     $bytes = ceil(4 * $len / floor(32 / $bits_per_char));
     // Pad to 4 byte boundary
     $bytes += (4 - $bytes % 4) % 4;
     // Fetch some random data blocks
     $data = Crypto::random($bytes);
     $mask = (1 << $bits_per_char) - 1;
     $loops = (int) (32 / $bits_per_char);
     $output = '';
     $ints = unpack('V*', $data);
     foreach ($ints as $int) {
         for ($i = $loops; $i > 0; $i--) {
             $output .= $chars[($int & $mask) % $char_count];
             $int >>= $bits_per_char;
         }
     }
     return substr($output, 0, $len);
 }
Beispiel #28
0
/**
 * Create random value on give criteria
 *
 * @param int $length
 * @param string $type (mixed, chars, digits)
 * @return string
 */
function generateRandomString($length, $type = null)
{
    if (!Reg::get('packageMgr')->isPluginLoaded('Crypto', 'Crypto')) {
        throw new RuntimeException("Crypto plugin is not loaded!");
    }
    if ($length === null) {
        $length = 12;
    }
    if ($type === null) {
        $type = 'mixed';
    }
    if ($type != 'mixed' && $type != 'chars' && $type != 'digits') {
        return false;
    }
    $rand_value = '';
    while (strlen($rand_value) < $length) {
        if ($type == 'digits') {
            $char = Crypto::s_rand(0, 9);
        } else {
            $char = chr(Crypto::s_rand(0, 255));
        }
        if ($type == 'mixed') {
            if (preg_match('/^[a-z0-9]$/i', $char)) {
                $rand_value .= $char;
            }
        } elseif ($type == 'chars') {
            if (preg_match('/^[a-z]$/i', $char)) {
                $rand_value .= $char;
            }
        } elseif ($type == 'digits') {
            if (preg_match('^[0-9]$', $char)) {
                $rand_value .= $char;
            }
        }
    }
    return $rand_value;
}
Beispiel #29
0
 if (Settings::i()->captcha_private) {
     if (!isset($login['captcha_response'])) {
         die(Submission::createResult("Please validate the captcha"));
     }
     $reCaptcha = new ReCaptcha(Settings::i()->captcha_private);
     $resp = $reCaptcha->verifyResponse($_SERVER["REMOTE_ADDR"], $login['captcha_response']);
     if (!$resp->success) {
         die(Submission::createResult("Please validate the Captcha"));
     }
 }
 $key = Crypto::GenerateKey($login['username']);
 $find = DbManager::i()->select("sf_members", array("iv", "userid"), array("key" => base64_encode(base64_encode($key))));
 if ($find !== false) {
     if (!is_array($find)) {
         $iv = base64_decode(base64_decode($find->iv));
         $password = base64_encode(base64_encode(Crypto::EncryptString($key, $iv, $login['password'])));
         $find = DbManager::i()->select("sf_members", array("userid"), array("password" => $password));
         if ($find !== false && !is_array($find)) {
             echo Submission::createResult("login successful", true);
             $_SESSION['login'] = 1;
             $_SESSION['userid'] = $find->userid;
             $find = DbManager::i()->select("sf_carts", array("cart"), array("userid" => $find->userid));
             if ($find !== false && !is_array($find)) {
                 //cart already exists for user
                 if ($find->cart != "e30=" && strlen($find->cart) != 4) {
                     //not empty cart - overwrite with saved one from DB
                     $_SESSION['shopping-cart'] = $find->cart;
                 } else {
                     //empty cart, use session cart
                     if (isset($_SESSION['shopping-cart'])) {
                         DbManager::i()->update("sf_carts", array("cart" => $_SESSION['shopping-cart']), array("userid" => intval($_SESSION['userid'])));
Beispiel #30
0
 /**
  * Store a value in an encrypted cookie
  * 
  * @param string $name
  * @param mixed $value
  * @param int $expire    (defaults to 0)
  * @param string $path   (defaults to '/')
  * @param string $domain (defaults to NULL)
  * @param bool $secure   (defaults to TRUE)
  * @param bool $httponly (defaults to TRUE)
  * @return bool
  */
 public function store(string $name, $value, int $expire = 0, string $path = '/', $domain = null, bool $secure = true, bool $httponly = true) : bool
 {
     return \setcookie($name, Crypto::encrypt(\json_encode($value), $this->key), $expire, $path, $domain, $secure, $httponly);
 }