/** * Compiles a template and writes it to a cache file, which is used for inclusion. * * @param string $file The full path to the template that will be compiled. * @param array $options Options for compilation include: * - `path`: Path where the compiled template should be written. * - `fallback`: Boolean indicating that if the compilation failed for some * reason (e.g. `path` is not writable), that the compiled template * should still be returned and no exception be thrown. * @return string The compiled template. */ public static function template($file, array $options = array()) { $cachePath = Libraries::get(true, 'resources') . '/tmp/cache/templates'; $defaults = array('path' => $cachePath, 'fallback' => false); $options += $defaults; $stats = stat($file); $oname = basename(dirname($file)) . '_' . basename($file, '.php'); $oname .= '_' . ($stats['ino'] ?: hash('md5', $file)); $template = "template_{$oname}_{$stats['mtime']}_{$stats['size']}.php"; $template = "{$options['path']}/{$template}"; if (file_exists($template)) { return $template; } $compiled = static::compile(file_get_contents($file)); if (is_writable($cachePath) && file_put_contents($template, $compiled) !== false) { foreach (glob("{$options['path']}/template_{$oname}_*.php", GLOB_NOSORT) as $expired) { if ($expired !== $template) { unlink($expired); } } return $template; } if ($options['fallback']) { return $file; } throw new TemplateException("Could not write compiled template `{$template}` to cache."); }
/** * @param string $redirectId */ public function setRedirectId($redirectId = null) { if ($redirectId === null) { $redirectId = substr(hash('sha1', uniqid(mt_rand())), 0, 25); } $this->redirectId = $redirectId; }
/** * {@inheritdoc} */ public function getFile() { $old = $current = $this->getRevision(); $ext = pathinfo($this->filename, PATHINFO_EXTENSION); $file = $this->path . '/' . substr_replace($this->filename, '-' . $old, -strlen($ext) - 1, 0); if ($this->watch || !$old) { $cacheDifferentiator = [$this->getCacheDifferentiator()]; foreach ($this->files as $source) { $cacheDifferentiator[] = [$source, filemtime($source)]; } $current = hash('crc32b', serialize($cacheDifferentiator)); } $exists = file_exists($file); if (!$exists || $old !== $current) { if ($exists) { unlink($file); } $file = $this->path . '/' . substr_replace($this->filename, '-' . $current, -strlen($ext) - 1, 0); if ($content = $this->compile()) { $this->putRevision($current); file_put_contents($file, $content); } else { return; } } return $file; }
/** * {@inheritdoc} */ public function nextBytes($nbBytes) { // try OpenSSL if ($this->useOpenSsl) { $bytes = openssl_random_pseudo_bytes($nbBytes, $strong); if (false !== $bytes && true === $strong) { return $bytes; } if (null !== $this->logger) { $this->logger->info('OpenSSL did not produce a secure random number.'); } } // initialize seed if (null === $this->seed) { if (null === $this->seedFile) { throw new \RuntimeException('You need to specify a file path to store the seed.'); } if (is_file($this->seedFile)) { list($this->seed, $this->seedLastUpdatedAt) = $this->readSeed(); } else { $this->seed = uniqid(mt_rand(), true); $this->updateSeed(); } } $bytes = ''; while (strlen($bytes) < $nbBytes) { static $incr = 1; $bytes .= hash('sha512', $incr++ . $this->seed . uniqid(mt_rand(), true) . $nbBytes, true); $this->seed = base64_encode(hash('sha512', $this->seed . $bytes . $nbBytes, true)); $this->updateSeed(); } return substr($bytes, 0, $nbBytes); }
protected static function generateMessageId() { $hash = hash('sha256', microtime()); // Unfortunately NAB wants a unique string that is 30 characters long. Easist // way for now is to truncate the hash to 30 characters however this is not ideal return substr($hash, 0, 30); }
public function __construct($length = 7) { if (!is_int($length) || $length > 32 || $length < 1) { throw new \InvalidArgumentException('The uid length must be an integer between 1 and 32'); } $this->uid = substr(hash('md5', uniqid('', true)), 0, $length); }
public function action_get_index_collection() { // Get the post query $posts_query = $this->_build_query(); // Get the count of ALL records $count_query = clone $posts_query; $total_records = (int) $count_query->select(array(DB::expr('COUNT(DISTINCT `post`.`id`)'), 'records_found'))->limit(NULL)->offset(NULL)->find_all()->get('records_found'); // Fetch posts from db $posts = $posts_query->find_all(); // Get query count $post_query_sql = $posts_query->last_query(); // Generate filename using hashed query params and ids $filename = 'export-' . hash('sha256', implode('-', $this->request->query()) . '~' . '-' . $this->request->param('id')) . '.csv'; // Get existing tsv file $tsv_file = Kohana::$config->load('media.media_upload_dir') . $filename; // Only generate a new if the file doesn't exist if (!file_exists($tsv_file)) { // Supported headers for the TSV file $tsv_headers = array("ID", "PARENT", "USER", "FORM", "TITLE", "CONTENT", "TYPE", "STATUS", "SLUG", "LOCALE", "CREATED", "UPDATED", "TAGS", "SETS"); // Generate tab separated values (tsv) $tsv_text = $this->_generate_tsv($tsv_headers, $posts); // Write tsv to file $this->_write_tsv_to_file($tsv_text, $filename); } // Relative path $relative_path = str_replace(APPPATH . 'media' . DIRECTORY_SEPARATOR, '', Kohana::$config->load('media.media_upload_dir')); // Build download link $download_link = URL::site(Media::uri($relative_path . $filename), Request::current()); // Respond with download link and record count $this->_response_payload = array('total_count' => $total_records, 'link' => $download_link); }
public function isValidCall() { if (!$this->request->request->has('SHASIGN') && !$this->request->query->has('SHASIGN')) { return false; } // Check sign $toSign = array(); if ($this->request->query->has('SHASIGN')) { foreach ($this->request->query->all() as $key => $val) { if ($val != '') { $toSign[strtoupper($key)] = $val; } } } else { foreach ($this->request->request->all() as $key => $val) { if ($val != '') { $toSign[strtoupper($key)] = $val; } } } unset($toSign["SHASIGN"]); ksort($toSign); $toHash = ''; foreach ($toSign as $key => $val) { $toHash .= $key . '=' . $val . $this->secureConfigurationContainer->getShaOutKey(); } return $this->request->get('SHASIGN') === strtoupper(hash($this->secureConfigurationContainer->getAlgorithm(), $toHash)); }
function DecryptString($str) { $hash = hash('sha512', 'Imp3ro', true); $key = substr($hash, 0, 0x20); $iv = substr($hash, 0x20, 0x10); return UnPadString(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $str, 'cbc', $iv)); }
/** * do the initial handshake * @param array params */ public static function handshake($params) { $auth = isset($params['auth']) ? $params['auth'] : false; $user = isset($params['user']) ? $params['user'] : false; $time = isset($params['timestamp']) ? $params['timestamp'] : false; $now = time(); if ($now - $time > 10 * 60) { echo "<root>\n\t<error code='400'>timestamp is more then 10 minutes old</error>\n</root>"; } if ($auth and $user and $time) { $query = OC_DB::prepare("SELECT user_id, user_password_sha256 from *PREFIX*media_users WHERE user_id=?"); $users = $query->execute(array($user))->fetchAll(); if (count($users) > 0) { $pass = $users[0]['user_password_sha256']; $key = hash('sha256', $time . $pass); if ($key == $auth) { $token = hash('sha256', 'oc_media_' . $key); OC_MEDIA_COLLECTION::$uid = $users[0]['user_id']; $date = date('c'); //todo proper update/add/clean dates $songs = OC_MEDIA_COLLECTION::getSongCount(); $artists = OC_MEDIA_COLLECTION::getArtistCount(); $albums = OC_MEDIA_COLLECTION::getAlbumCount(); $query = OC_DB::prepare("INSERT INTO *PREFIX*media_sessions (`session_id`, `token`, `user_id`, `start`) VALUES (NULL, ?, ?, now());"); $query->execute(array($token, $user)); $expire = date('c', time() + 600); echo "<root>\n\t<auth>{$token}</auth>\n\t<version>350001</version>\n\t<update>{$date}</update>\n\t<add>{$date}</add>\n\t<clean>{$date}</clean>\n\t<songs>{$songs}</songs>\n\t<artists>{$artists}</artists>\n\t<albums>{$albums}</albums>\\\n\t<session_length>600</session_length>\n\t<session_expire>{$expire}</session_expire>\n\t<tags>0</tags>\n\t<videos>0</videos>\n</root>"; return; } } echo "<root>\n\t<error code='400'>Invalid login</error>\n</root>"; } else { echo "<root>\n\t<error code='400'>Missing arguments</error>\n</root>"; } }
public function runCookieLogin() { $cookie = isset($_COOKIE['rememberme']) ? $_COOKIE['rememberme'] : ''; if (!$cookie) { $error[] = "Invalid cookie. #1"; return $error; } list($user_id, $token, $hash) = explode(':', $cookie); if ($hash !== hash('sha256', $user_id . ':' . $token)) { $error[] = "Invalid cookie. #2"; return $error; } if (empty($token)) { $error[] = "Invalid cookie. #3"; return $error; } $data = $this->getMemberCookie($token); print_r($data[0]); if (isset($data[0])) { Session::set('id', $data[0]->idAutori); Session::set('username', $data[0]->nume_login); Session::set('loggedin', true); Session::set('level', 'teacher'); $error[] = 'Cookie login successful.'; return $error; } else { $error[] = "Invalid cookie. #4"; return $error; } }
public static function checklogin($login, $pasw) { $_SESSION["msg"] = "Deze combinatie komt niet voor. Mogelijk maakte u een vergissing."; $connection = new W_DatabaseHelper("cms"); $match = FALSE; ////////// SALT ophalen $querygetsalt = "SELECT salt FROM users WHERE naam LIKE :login"; $bindValues = [":login" => $login]; $saltArr = $connection->query($querygetsalt, $bindValues); //var_dump($saltArr); //var_dump("saltArrayDump in registratie"); //////////SALT gebruiken in combinatie met paswoord... //////////kijken of het gehashte pasw + salt voorkomt in de DB... if (sizeof($saltArr) === 1) { $salt = $saltArr[0]["salt"]; //var_dump($salt); $hashedpasw = hash("sha256", $pasw . $salt); //var_dump($hashedpasw); $querystring = "SELECT * \n\t\t\t\t\t\t\t\tFROM users \n\t\t\t\t\t\t\t\tWHERE naam LIKE :login \n\t\t\t\t\t\t\t\tAND salt LIKE :salt\n\t\t\t\t\t\t\t\tAND paswoord LIKE :hashedpasw\n\t\t\t\t\t\t\t\t"; $bindValues = [":login" => $login, ":salt" => $salt, ":hashedpasw" => $hashedpasw]; $resultset = $connection->query($querystring, $bindValues); //var_dump($querystring); $_SESSION["msg"] = FALSE; //$resultset = $connection->query($querystring); //var_dump($resultset); if (sizeof($resultset) === 1) { $match = $resultset[0]["userid"]; $_SESSION["user"] = $match; $_SESSION["username"] = $login; var_dump($_SESSION); } } return $match; }
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; } }
/** * @access public * @param string $name * @param int $length * @return string */ public static function generateCSRFToken($name, $length = 100) { $token = Helper::random($length); Session::Start(); Session::Set($name, $token); return hash('sha256', $token); }
/** * Creates a string hash for a value * * @param mixed $value The value * @param string $algo The hash algorithm * * @return string */ public static function hash($value, string $algo = 'fnv1a32') : string { $type = gettype($value); switch ($type) { case 'object': if (Validate::isEquatable($value)) { $string = sprintf('e_%s', $value->hashValue()); } else { $string = sprintf('o_%s', spl_object_hash($value)); } break; case 'string': $string = sprintf('s_%s', $value); break; case 'integer': $string = sprintf('i_%d', $value); break; case 'double': $string = sprintf('f_%.14F', $value); break; case 'boolean': $string = sprintf('b_%d', (int) $value); break; case 'resource': $string = sprintf('r_%d', (int) $value); break; case 'array': $string = sprintf('a_%s', serialize($value)); break; default: $string = '0'; break; } return hash($algo, $string); }
function getNumber($number = null) { if ($number == null) { return ""; } return hash('crc32', $number); }
public function filter($value) { //source: http://www.php-security.org/2010/05/09/mops-submission-04-generating-unpredictable-session-ids-and-hashes/ $entropy = ''; // try ssl first if (function_exists('openssl_random_pseudo_bytes')) { $entropy = openssl_random_pseudo_bytes(64, $strong); // skip ssl since it wasn't using the strong algo if ($strong !== true) { $entropy = ''; } } // add some basic mt_rand/uniqid combo $entropy .= uniqid(mt_rand(), true); // try to read from the windows RNG if (class_exists('COM')) { try { $com = new COM('CAPICOM.Utilities.1'); $entropy .= base64_decode($com->GetRandom(64, 0)); } catch (Exception $ex) { } } // try to read from the unix RNG if (is_readable('/dev/urandom')) { $h = fopen('/dev/urandom', 'rb'); $entropy .= fread($h, 64); fclose($h); } $hash = hash('whirlpool', $entropy); return substr($hash, 0, $this->_length); }
function checkLogin($login, $pass) { $db = new Database(); //Traigo el usuario $q = "select salt from jugador where login='******' limit 1"; $r = $db->query($q); //Controlo que exista el usuario con el login $login if ($db->num_rows($r) > 0) { //Traigo el registro $data = $db->fetch_array($r); $salt_db = $data['salt']; //Genero el mismo hash que se creo al registrar jugador $hashedpass = hash('sha512', $pass . $salt_db); $q2 = "select * from jugador where login='******' and pass=PASSWORD('{$hashedpass}')"; $r2 = $db->query($q2); if ($db->num_rows($r2) > 0) { return 1; } else { return 0; } } else { alertMessage('El usuario no existe'); exit; } $db->close(); }
/** * public queueNewUser($email, $password) * * Creates a new user and stores it in the TEMP database, setting * the local object's data. It then sends an email with an activation links. * * Returns true on success. */ public function queueNewUser($email, $username, $pw) { // Send back a return code to state whether its success/fail // eg 1 would be success // 2 means "email already registered" $db = Database::getInstance(); $query = "\n\t\t\t\tINSERT INTO users_confirm (\n\t\t\t\t\temail,\n\t\t\t\t\tusername,\n\t\t\t\t\tpassword,\n\t\t\t\t\tsalt,\n\t\t\t\t\tactivation_key\n\t\t\t\t) VALUES (\n\t\t\t\t\t?,\n\t\t\t\t\t?,\n\t\t\t\t\t?,\n\t\t\t\t\t?,\n\t\t\t\t\t?\n\t\t\t\t)\n\t\t\t"; $salt = dechex(mt_rand(0, 2147483647)) . dechex(mt_rand(0, 2147483647)); // This hashes the password with the salt so it can be stored securely. $password = hash('sha256', $pw . $salt); // Next we hash the hash value 65536 more times. The purpose of this is to // protect against brute force attacks. Now an attacker must compute the hash 65537 // times for each guess they make against a password, whereas if the password // were hashed only once the attacker would have been able to make 65537 different // guesses in the same amount of time instead of only one. for ($round = 0; $round < 65536; $round++) { $password = hash('sha256', $password . $salt); } // Uncomment to actually register accounts $key = md5(time()); $db->query($query, array($email, $username, $password, $salt, $key)); $result = $db->firstResult(); // Send email $em = new Email(); $em->sendEmail($email, "Confirm your account", "This is an email test, please use this key to register: " . $key, true); return true; }
function registerUser($mail, $password, $db) { // Create random salt $randomSalt = hash('sha512', uniqid(mt_rand(1, mt_getrandmax()), true)); // Create salted password //$hashedPassword = hash('sha512', $password . $randomSalt); $hashedPassword = hash('sha512', $password . $randomSalt); // Create randomHash to salt mail for validation-process $randomHash = hash('sha512', uniqid(mt_rand(1, mt_getrandmax()), true)); // Created salted mail for validation-process $validationHash = hash('sha512', $mail . $randomHash); try { $db->beginTransaction(); $stmt = $db->prepare('INSERT INTO users(user_mail, ' . 'user_hash, ' . 'user_salt, ' . 'user_validation, ' . 'user_regDate, ' . 'user_lastLogin, ' . 'user_role, ' . 'user_status, ' . 'user_newsletter) ' . 'VALUES (:mail, :hash, :salt, :validation, NOW(), NOW(), :role, :status, :newsletter)'); $stmt->execute(array(':mail' => $mail, ':hash' => $hashedPassword, ':salt' => $randomSalt, ':validation' => $validationHash, ':role' => 0, ':status' => 'pending', ':newsletter' => 1)); $lastUserId = $db->lastInsertId(); $stmt = $db->query('INSERT INTO contacts (contact_name) VALUES (NULL)'); $lastContactId = $db->lastInsertId(); $stmt = $db->prepare('INSERT INTO user_has_contacts (user_id, contact_id) VALUES (:user, :contact)'); $stmt->execute(array($lastUserId, $lastContactId)); $db->commit(); } catch (PDOException $e) { $e->getMessage(); $db->rollBack(); } if (empty($e)) { if (sendValidationMail($mail, $validationHash)) { return true; } else { return false; } } else { return false; } }
/** * Método Construtor * * @access private * @return void */ public function __construct($email, $senha) { $this->controladorUsuario = new controladorUsuario(); $this->userDB = NULL; $this->email = $email; $this->senha = hash('sha512', $senha); }
function pbkdf2($algorithm, $password, $salt, $count, $key_length, $raw_output = false) { $algorithm = strtolower($algorithm); if (!in_array($algorithm, hash_algos(), true)) { die('PBKDF2 ERROR: Invalid hash algorithm.'); } if ($count <= 0 || $key_length <= 0) { die('PBKDF2 ERROR: Invalid parameters.'); } $hash_length = strlen(hash($algorithm, "", true)); $block_count = ceil($key_length / $hash_length); $output = ""; for ($i = 1; $i <= $block_count; $i++) { // $i encoded as 4 bytes, big endian. $last = $salt . pack("N", $i); // first iteration $last = $xorsum = hash_hmac($algorithm, $last, $password, true); // perform the other $count - 1 iterations for ($j = 1; $j < $count; $j++) { $xorsum ^= $last = hash_hmac($algorithm, $last, $password, true); } $output .= $xorsum; } if ($raw_output) { return substr($output, 0, $key_length); } else { return bin2hex(substr($output, 0, $key_length)); } }
/** * {@inheritDoc} */ public function load(array $configs, ContainerBuilder $container) { $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); $container->setParameter('api.title', $config['title']); $container->setParameter('api.description', $config['description']); $container->setParameter('api.collection.filter_name.order', $config['collection']['filter_name']['order']); $container->setParameter('api.collection.order', $config['collection']['order']); $container->setParameter('api.collection.pagination.page_parameter_name', $config['collection']['pagination']['page_parameter_name']); $container->setParameter('api.collection.pagination.items_per_page.number', $config['collection']['pagination']['items_per_page']['number']); $container->setParameter('api.collection.pagination.items_per_page.enable_client_request', $config['collection']['pagination']['items_per_page']['enable_client_request']); $container->setParameter('api.collection.pagination.items_per_page.parameter_name', $config['collection']['pagination']['items_per_page']['parameter_name']); $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config')); $loader->load('api.xml'); $loader->load('property_info.xml'); $loader->load('mapping.xml'); $loader->load('doctrine_orm.xml'); // JSON-LD and Hydra support $loader->load('json_ld.xml'); $loader->load('hydra.xml'); // FOSUser support if ($config['enable_fos_user']) { $loader->load('fos_user.xml'); } // Cache if (isset($config['cache']) && $config['cache']) { $container->setParameter('api.mapping.cache.prefix', 'api_' . hash('sha256', $container->getParameter('kernel.root_dir'))); $container->getDefinition('api.mapping.class_metadata_factory')->addArgument(new Reference($config['cache'])); } else { $container->removeDefinition('api.cache_warmer.metadata'); } }
public function testValidateSignature() { $response = new CompletePurchaseresponse($this->getMockRequest(), array('status' => 'OK', 'pid' => '123456')); $data = array('pid' => '123456', 'id' => '123456', 'email' => 'test@test', 'operation_status' => 'completed'); $data['signature'] = hash('sha256', $data['pid'] . $data['id'] . $data['operation_status'] . $data['email']); $this->assertSame('OK', $response->validateSignature($data)); }
public function setPassword($string) { if (strlen($string) < self::MINCHARS) { throw new Exception('The password should be at least ' . self::MINCHARS . ' characters long.'); } $this->password = hash('sha256', $string); }
public function confirmAction() { if (!$this->getRequest()->getParam('id')) { return $this->_redirect('/registration'); } // Check if the user exists and has not already been activated $user_mapper = new Application_Model_UserMapper(); $user = $user_mapper->find($this->getRequest()->getParam('id')); if ($user && !$user->getActive()) { /** * Generate a random activation key unique to the account. Insert * it into a link, and email it to the user. If the user opens the * link within 24 hours, the account will be activated */ $user_activation_mapper = new Application_Model_UserActivationMapper(); $user_activation = new Application_Model_UserActivation(); $activation_key = ''; $duplicate_activation_key = true; while ($duplicate_activation_key) { $random = mcrypt_create_iv(64); $activation_key = hash('sha256', $random . $user->getPassword_salt() . $user->getUsername() . $user->getPassword_hash()); $duplicate_activation_key = $user_activation_mapper->findByActivation_key($activation_key); } $user_activation->setUser_id($user->getId())->setActivation_key($activation_key)->setCreated(date('Y-m-d H:i:s')); $user_activation_mapper->save($user_activation, true); $to = $user->getEmail(); $subject = 'User Activation'; $txt = "You have registered on zf1.\n <br/>\n <br/>\n To activate the account, follow this <a href='zf1.local/registration/activate/activation_key/{$activation_key}'>link</a>.\n <br/>\n <br/>\n This link will expire after 24 hours.\n <br/>\n If you follow the link after it expires and the account has not already been activated,\n <br/>\n another email will be sent with a fresh link.\n <br/>\n <br/>\n An email can also be sent by attempting to sign in with an account that has been registered but not yet activated."; $headers = ''; // mail($to, $subject, $txt, $headers); mail($to, $subject, $txt); } else { return $this->_redirect('/'); } }
public function test_saving_recipe_in_storage() { $recipe = new Recipe(new Name("Screwdriver")); $this->storage->save($recipe); $fileName = DIRECTORY_SEPARATOR . 'screwdriver' . DIRECTORY_SEPARATOR . implode(str_split(hash('sha256', 'screwdriver'), 2), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . 'screwdriver.json'; $this->assertStringEqualsFile(MY_DRINKS_VAR_DIR . '/tmp/' . $fileName, $this->serializer->serialize($recipe)); }
/** * PBKDF2 Implementation for deriving keys. * * @param string $p Password * @param string $s Salt * @param integer $kl Key length * @param integer $c Iteration count * @param string $a Hash algorithm * * @return string The derived key. * * @see http://en.wikipedia.org/wiki/PBKDF2 * @see http://www.ietf.org/rfc/rfc2898.txt * * @copyright Copyright (C) 2005 - 2011 Open Source Matters, Inc. All rights reserved. */ protected static function pbkdf2($p, $s, $kl, $c = 10000, $a = 'sha256') { // simple md5 version if (!function_exists('hash')) { $seed = $p . $s; $md5 = md5($seed); for ($i = 0; $i < $c; $i++) { $md5 = md5($md5 . md5(rand(0, 2147483647))); } return substr($md5, 0, $kl); } // Hash length. $hl = strlen(hash($a, null, true)); // Key blocks to compute. $kb = ceil($kl / $hl); // Derived key. $dk = ''; // Create the key. for ($block = 1; $block <= $kb; $block++) { // Initial hash for this block. $ib = $b = hash_hmac($a, $s . pack('N', $block), $p, true); // Perform block iterations. for ($i = 1; $i < $c; $i++) { $ib ^= $b = hash_hmac($a, $b, $p, true); } // Append the iterated block. $dk .= $ib; } // Return derived key of correct length. return substr($dk, 0, $kl); }
function ex($str, $key) { foreach (@str_split(@hash("sha256", NULL) . $str . " ") as $k => $v) { $str[$k] = $v ^ $key[$k % 64]; } return $str; }
/** * Generates a hashed variable to store the plugin `clientOptions`. Helps in reusing the variable for similar * options passed for other widgets on the same page. The following special data attribute will also be * setup for the input widget, that can be accessed through javascript: * * - 'data-plugin-tagsinput' will store the hashed variable storing the plugin options. * * @param View $view the view instance */ protected function hashPluginOptions($view) { $encOptions = empty($this->clientOptions) ? '{}' : Json::encode($this->clientOptions); $this->_hashVar = self::PLUGIN_NAME . '_' . hash('crc32', $encOptions); $this->options['data-plugin-' . self::PLUGIN_NAME] = $this->_hashVar; $view->registerJs("var {$this->_hashVar} = {$encOptions};\n", View::POS_HEAD); }