本文整理汇总了PHP中hash_equals函数的典型用法代码示例。如果您正苦于以下问题:PHP hash_equals函数的具体用法?PHP hash_equals怎么用?PHP hash_equals使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了hash_equals函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: verify
public function verify($password, $hash)
{
$key = hash(self::HASH_PRIMITIVE, $password, true);
$hash = base64_decode($hash);
$header = substr($hash, 0, self::HEADER_SIZE);
$iv = substr($hash, self::HEADER_SIZE, self::IV_LENGTH);
$ciphertext = substr($hash, self::HEADER_SIZE + self::IV_LENGTH);
$decrypted = openssl_decrypt($ciphertext, self::CIPHER_PRIMITIVE, $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $iv);
list(, $version, $rounds, $pointerSize, $dataSize) = unpack('C*', $header);
$iterationCount = pow(2, $rounds);
$dataSizeDecoded = pow(2, $dataSize);
if ($version !== 1) {
throw new \RuntimeException("Unknown version encountered");
}
if (strlen($decrypted) !== self::HASH_LENGTH + $iterationCount * $pointerSize) {
throw new \RuntimeException("Invalid data payload, was it truncated?");
}
$h = hash_init(self::HASH_PRIMITIVE);
for ($i = 0; $i < $iterationCount; $i++) {
$pointer = substr($decrypted, $i * $pointerSize, $pointerSize);
hash_update($h, $this->read($pointer, $dataSizeDecoded));
}
$test = hash_final($h, true);
return hash_equals($test, substr($decrypted, $iterationCount * $pointerSize));
}
示例2: equals
/**
* Compares two strings.
*
* This method implements a constant-time algorithm to compare strings.
* Regardless of the used implementation, it will leak length information.
*
* @param string $knownString The string of known length to compare against
* @param string $userInput The string that the user can control
*
* @return bool true if the two strings are the same, false otherwise
*/
public static function equals($knownString, $userInput)
{
static $exists = null;
if (null === $exists) {
$exists = function_exists('hash_equals');
}
$knownString = (string) $knownString;
$userInput = (string) $userInput;
if ($exists) {
return hash_equals($knownString, $userInput);
}
$knownLen = strlen($knownString);
$userLen = strlen($userInput);
// Extend the known string to avoid uninitialized string offsets
$knownString .= $userInput;
// Set the result to the difference between the lengths
$result = $knownLen - $userLen;
// Note that we ALWAYS iterate over the user-supplied length
// This is to mitigate leaking length information
for ($i = 0; $i < $userLen; ++$i) {
$result |= ord($knownString[$i]) ^ ord($userInput[$i]);
}
// They are only identical strings if $result is exactly 0...
return 0 === $result;
}
示例3: verify
/**
* To prevent timing attacks we are using PHP 5.6 native function hash_equals,
* in case of PHP < 5.6 a timing safe equals comparison function
*
* more info here:
* http://blog.ircmaxell.com/2014/11/its-all-about-time.
* http://blog.ircmaxell.com/2014/11/its-all-about-time.html
*
*
* @inheritdoc
*/
public function verify($key, $signature, $input)
{
$signedInput = $this->sign($input, $key);
if (version_compare(PHP_VERSION, '5.6.0', '>=')) {
return hash_equals($signature, $signedInput);
}
return $this->timingSafeEquals($signature, $signedInput);
}
示例4: validateToken
public function validateToken()
{
switch ($this->source) {
case self::TYPE_STRIPE:
if ('tok_' == substr($this->token, 0, 4)) {
return TRUE;
}
break;
case self::TYPE_COMP:
$secret = $_ENV['TOK_SECRET_COMP'];
goto join_COMPCASH;
case self::TYPE_CASH:
$secret = $_ENV['TOK_SECRET_CASH'];
join_COMPCASH:
if (FALSE === ($sepPos = strpos($this->token, ':'))) {
break;
}
$inputSecret = substr($this->token, 0, $sepPos);
if (hash_equals($secret, $inputSecret)) {
return TRUE;
}
break;
default:
break;
}
throw new BookingTokenException("Invalid token");
}
示例5: validate
/**
* Validate valid CSRF token
*
* @param string $token
* @return bool
*/
public function validate($token)
{
if ($token !== null && $this->getToken() !== null) {
return hash_equals($token, $this->getToken());
}
return false;
}
示例6: decrypt
/**
* Decrypt a string.
*
* @access public
* @static static method
* @param string $ciphertext
* @return string
* @throws Exception If $ciphertext is empty, or If functions don't exists
*/
public static function decrypt($ciphertext)
{
if (empty($ciphertext)) {
throw new Exception("the string to decrypt can't be empty");
}
if (!function_exists('openssl_cipher_iv_length') || !function_exists('openssl_decrypt')) {
throw new Exception("Encryption function don't exists");
}
// generate key used for authentication using ENCRYPTION_KEY & HMAC_SALT
$key = mb_substr(hash(self::HASH_FUNCTION, Config::get('ENCRYPTION_KEY') . Config::get('HMAC_SALT')), 0, 32, '8bit');
// split cipher into: hmac, cipher & iv
$macSize = 64;
$hmac = mb_substr($ciphertext, 0, $macSize, '8bit');
$iv_cipher = mb_substr($ciphertext, $macSize, null, '8bit');
// generate original hmac & compare it with the one in $ciphertext
$originalHmac = hash_hmac('sha256', $iv_cipher, $key);
if (!function_exists("hash_equals")) {
throw new Exception("Function hash_equals() doesn't exist!");
}
if (!hash_equals($hmac, $originalHmac)) {
return false;
}
// split out the initialization vector and cipher
$iv_size = openssl_cipher_iv_length(self::CIPHER);
$iv = mb_substr($iv_cipher, 0, $iv_size, '8bit');
$cipher = mb_substr($iv_cipher, $iv_size, null, '8bit');
return openssl_decrypt($cipher, self::CIPHER, $key, OPENSSL_RAW_DATA, $iv);
}
示例7: checkPasswordForUser
public static function checkPasswordForUser($password, UserEntity $user)
{
if (hash_equals($user->getPassword(), crypt($password, $user->getPassword()))) {
return true;
}
return false;
}
示例8: validateHash
public function validateHash($hash, $password)
{
if (hash_equals($hash, crypt($password, $hash))) {
return true;
}
return false;
}
示例9: hashCheck
public function hashCheck($known, $user)
{
if (function_exists('hash_equals')) {
return hash_equals($known, $user);
}
return $this->hash_equals($known, $user);
}
示例10: check
public static function check($userToken)
{
if ($sessionToken = Session::get('csrf_token')) {
return hash_equals($sessionToken, $userToken);
}
return false;
}
示例11: prepare_item_for_response
/**
* Prepare a single user output for response
*
* @param object $user User object.
* @param WP_REST_Request $request Request object.
* @return WP_REST_Response Response data.
*/
public function prepare_item_for_response($user, $request)
{
$roles = $user->roles;
if (empty($roles)) {
$isadmin = false;
} else {
$isadmin = hash_equals($roles[0], 'administrator');
}
$user_id = $user->ID;
$user_blogs = get_blogs_of_user($user_id);
$site = urldecode($request['site']);
$data = array('id' => $user->ID, 'username' => $user->user_login, 'name' => $user->display_name, 'email' => $user->user_email, 'admin' => $isadmin, 'role' => $roles[0], 'site' => $_SERVER['SERVER_NAME'], 'host' => $_SERVER['HTTP_HOST'], 'blogs' => $user_blogs);
$context = !empty($request['context']) ? $request['context'] : 'embed';
$data = $this->filter_response_by_context($data, $context);
$data = $this->add_additional_fields_to_object($data, $request);
// Wrap the data in a response object
$response = rest_ensure_response($data);
//$response->add_links( $this->prepare_links( $user ) );
/**
* Filter user data returned from the REST API.
*
* @param WP_REST_Response $response The response object.
* @param object $user User object used to create response.
* @param WP_REST_Request $request Request object.
*/
return apply_filters('rest_prepare_user', $response, $user, $request);
}
开发者ID:Afrozaar,项目名称:wp-api-v2-afrozaar-extras,代码行数:34,代码来源:class-wp-rest-users-extras-controller.php
示例12: __construct
/**
* Install constructor.
*
* @param \Twig_Environment $twig
* @param array $data
*/
public function __construct(\Twig_Environment $twig, array $data = [])
{
if (!Halite::isLibsodiumSetupCorrectly()) {
echo \file_get_contents(\dirname(__DIR__) . '/error_pages/old-libsodium.html');
exit(255);
}
$this->twig = $twig;
$this->data = $data;
$this->data['airship_version'] = \AIRSHIP_VERSION;
$this->csrf = new CSRF();
// We do this to prevent someone from coming along and reading your
// half-finished configuration settings (e.g. database passwords):
if (empty($this->data['step'])) {
$this->data['step'] = 1;
}
if (empty($this->data['token'])) {
$this->data['token'] = Base64::encode(\random_bytes(33));
\setcookie('installer', $this->data['token'], \time() + 8640000, '/');
\Airship\redirect('/');
} elseif (empty($_COOKIE['installer'])) {
echo 'No installer authorization token found.', "\n";
exit(255);
} elseif (!\hash_equals($this->data['token'], $_COOKIE['installer'])) {
// This effectively locks unauthorized users out of the system while installing
echo 'Invalid installer authorization token.', "\n";
exit(255);
}
$dirs = ['comments', 'csp_hash', 'csp_static', 'hash', 'markdown', 'static', 'twig'];
foreach ($dirs as $d) {
if (!\is_dir(\dirname(__DIR__) . '/tmp/cache/' . $d)) {
\mkdir(\dirname(__DIR__) . '/tmp/cache/' . $d, 0775, true);
}
}
}
示例13: decode
/**
* Decodes JSON Web Token and set data in payload attribute.
*
* @return bool Indicate if token is valid
*/
public function decode()
{
$elements = explode('.', $this->value);
if (count($elements) !== 3) {
//invalid token format
return false;
}
list($b64Header, $b64Payload, $b64Signature) = $elements;
$headers = json_decode(base64_decode($b64Header));
$payload = json_decode(base64_decode($b64Payload));
$signature = base64_decode($b64Signature);
//check header
if (!$headers || !property_exists($headers, 'alg') || $headers->alg !== 'HS256' || !property_exists($headers, 'typ') || $headers->typ !== 'JWT') {
//invalid header
return false;
}
//check signature
if (!$signature || !hash_equals($signature, hash_hmac('sha256', $b64Header . '.' . $b64Payload, $this->key, true))) {
//invalid signature
return false;
}
if (!$payload || !property_exists($payload, 'exp') || $payload->exp < time()) {
//token expired
return false;
}
$this->payload = $payload;
//raw data is set, returns true
return true;
}
示例14: authenticate
/**
* {@inheritDoc}
*/
public function authenticate(RequestInterface $request)
{
$authHeader = AuthorizationHeader::createFromRequest($request);
$signature = $authHeader->getSignature();
// Check whether the timestamp is valid.
$comparison = $this->compareTimestamp($request, $this->expiry);
if (-1 == $comparison) {
throw new TimestampOutOfRangeException('Request is too old');
} elseif (1 == $comparison) {
throw new TimestampOutOfRangeException('Request is too far in the future');
}
// Load the API Key and sign the request.
if (!($key = $this->keyLoader->load($authHeader->getId()))) {
throw new KeyNotFoundException('API key not found');
}
// Generate the signature from the passed authorization header.
// If it matches the request signature, the request is authenticated.
$compareRequest = $request->withoutHeader('Authorization');
$authHeaderBuilder = new AuthorizationHeaderBuilder($compareRequest, $key);
$authHeaderBuilder->setRealm($authHeader->getRealm());
$authHeaderBuilder->setId($authHeader->getId());
$authHeaderBuilder->setNonce($authHeader->getNonce());
$authHeaderBuilder->setVersion($authHeader->getVersion());
$authHeaderBuilder->setCustomHeaders($authHeader->getCustomHeaders());
$compareAuthHeader = $authHeaderBuilder->getAuthorizationHeader();
$compareSignature = $compareAuthHeader->getSignature();
if (!hash_equals($compareSignature, $signature)) {
throw new InvalidSignatureException('Signature not valid');
}
return $key;
}
示例15: downloadAlbumAction
/**
* @Route("/album/{id}/download", requirements={
* "id": "\d+"
* })
* @Method({"GET", "OPTIONS"})
*/
public function downloadAlbumAction(Request $request, Album $album)
{
// Verify token
$secret = $uploadDir = $this->getParameter('secret') . '54 90df2!!fh++ gGZ)=';
$date = new \DateTime();
$time = $date->format('d-m-Y H:i');
$correct = hash('sha256', $secret . $time . $album->getId());
$token = $request->query->get('token');
if ($token === null) {
$token = '';
}
if (!hash_equals($correct, $token)) {
return new JsonResponse(array('message' => 'Invalid token.'), 403);
}
$uploadDir = $this->getParameter('photo_upload_dir');
$filename = $uploadDir . '/' . $album->getId() . '-' . $album->getTitle() . '.zip';
$zip = new \ZipArchive();
if ($zip->open($filename, \ZipArchive::CREATE) !== true) {
throw new Exception('Cannot open or create ZIP archive for file ' . $filename);
}
foreach ($album->getPhotos() as $photo) {
if ($zip->locateName($photo->getFilename()) === false) {
$zip->addFile($uploadDir . '/' . $photo->getFilename(), $photo->getFilename());
}
}
$zip->close();
$response = new BinaryFileResponse($filename);
$response->headers->set('Content-disposition', 'attachment;filename="' . $album->getTitle() . '.zip"');
return $response;
}