本文整理汇总了PHP中hash函数的典型用法代码示例。如果您正苦于以下问题:PHP hash函数的具体用法?PHP hash怎么用?PHP hash使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了hash函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: template
/**
* 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.");
}
示例2: pbkdf2
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));
}
}
示例3: hash
/**
* 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);
}
示例4: generateCSRFToken
/**
* @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);
}
示例5: nextBytes
/**
* {@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);
}
示例6: getFile
/**
* {@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;
}
示例7: action_get_index_collection
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);
}
示例8: generateMessageId
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);
}
示例9: queueNewUser
/**
* 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;
}
示例10: isValidCall
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));
}
示例11: handshake
/**
* 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>";
}
}
开发者ID:Teino1978-Corp,项目名称:Teino1978-Corp-owncloud_.htaccess-,代码行数:39,代码来源:owncloud_apps_media_lib_ampache.php
示例12: filter
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);
}
示例13: runCookieLogin
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;
}
}
示例14: checklogin
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;
}
示例15: _checkPassword
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;
}
}