hmacBase64 example


  public function testHmacBase64($data$key$expected_hmac) {
    $hmac = Crypt::hmacBase64($data$key);
    $this->assertEquals($expected_hmac$hmac, 'The correct hmac was not calculated.');
  }

  /** * Tests the hmacBase64 method with invalid parameters. * * @dataProvider providerTestHmacBase64Invalid * @covers ::hmacBase64 * * @param string $data * Data to hash. * @param string $key * Key to use in hashing process. */
public function testBlockContextualLinks() {
    $this->drupalLogin($this->drupalCreateUser([
      'administer views',
      'access contextual links',
      'administer blocks',
    ]));
    $block = $this->drupalPlaceBlock('views_block:test_view_block-block_1');
    $cached_block = $this->drupalPlaceBlock('views_block:test_view_block-block_1');
    $this->drupalGet('test-page');

    $id = 'block:block=' . $block->id() . ':langcode=en|entity.view.edit_form:view=test_view_block:location=block&name=test_view_block&display_id=block_1&langcode=en';
    $id_token = Crypt::hmacBase64($id, Settings::getHashSalt() . $this->container->get('private_key')->get());
    $cached_id = 'block:block=' . $cached_block->id() . ':langcode=en|entity.view.edit_form:view=test_view_block:location=block&name=test_view_block&display_id=block_1&langcode=en';
    $cached_id_token = Crypt::hmacBase64($cached_id, Settings::getHashSalt() . $this->container->get('private_key')->get());
    // @see \Drupal\contextual\Tests\ContextualDynamicContextTest:assertContextualLinkPlaceHolder()     // Check existence of the contextual link placeholders.     $this->assertSession()->responseContains('<div' . new Attribute(['data-contextual-id' => $id, 'data-contextual-token' => $id_token, 'data-drupal-ajax-container' => '']) . '></div>');
    $this->assertSession()->responseContains('<div' . new Attribute(['data-contextual-id' => $cached_id, 'data-contextual-token' => $cached_id_token, 'data-drupal-ajax-container' => '']) . '></div>');

    // Get server-rendered contextual links.     // @see \Drupal\contextual\Tests\ContextualDynamicContextTest:renderContextualLinks()     $post = ['ids[0]' => $id, 'ids[1]' => $cached_id, 'tokens[0]' => $id_token, 'tokens[1]' => $cached_id_token];
    $url = 'contextual/render?_format=json,destination=test-page';
    
$normalized['asset_group']['items'][$key] = array_diff_key($asset$group_keys$omit_keys);
      // If the version is set to -1, this means there is no version in the       // library definition. To ensure unique hashes when unversioned files       // change, replace the version with a hash of the file contents.       if ($asset['version'] === -1) {
        $normalized['asset_group']['items'][$key]['version'] = hash('xxh64', file_get_contents($asset['data']));
      }
    }
    // The asset array ensures that a valid hash can only be generated via the     // same code base. Additionally use the hash salt to ensure that hashes are     // not re-usable between different installations.     return Crypt::hmacBase64(serialize($normalized), Settings::getHashSalt());
  }

}
$php = new $this->storageClass($this->settings);
    $name = 'test.php';
    $php->save($name, '<?php');
    $expected_root_directory = $this->directory . '/test';
    if (substr($name, -4) === '.php') {
      $expected_directory = $expected_root_directory . '/' . substr($name, 0, -4);
    }
    else {
      $expected_directory = $expected_root_directory . '/' . $name;
    }
    $directory_mtime = filemtime($expected_directory);
    $expected_filename = $expected_directory . '/' . Crypt::hmacBase64($name$this->secret . $directory_mtime) . '.php';

    // Ensure the file exists and that it and the containing directory have     // minimal permissions. fileperms() can return high bits unrelated to     // permissions, so mask with 0777.     $this->assertFileExists($expected_filename);
    $this->assertSame(0444, fileperms($expected_filename) & 0777);
    $this->assertSame(0777, fileperms($expected_directory) & 0777);

    // Ensure the root directory for the bin has a .htaccess file denying web     // access.     $this->assertSame(file_get_contents($expected_root_directory . '/.htaccess'), FileSecurity::htaccessLines());

    
throw new BadRequestHttpException('No contextual ids specified.');
    }
    $ids = $request->request->all('ids');

    if (!$request->request->has('tokens')) {
      throw new BadRequestHttpException('No contextual ID tokens specified.');
    }
    $tokens = $request->request->all('tokens');

    $rendered = [];
    foreach ($ids as $key => $id) {
      if (!isset($tokens[$key]) || !hash_equals($tokens[$key], Crypt::hmacBase64($id, Settings::getHashSalt() . \Drupal::service('private_key')->get()))) {
        throw new BadRequestHttpException('Invalid contextual ID specified.');
      }
      $element = [
        '#type' => 'contextual_links',
        '#contextual_links' => _contextual_id_to_links($id),
      ];
      $rendered[$id] = $this->renderer->renderRoot($element);
    }

    return new JsonResponse($rendered);
  }

}

  public static function preRenderPlaceholder(array $element) {
    $token = Crypt::hmacBase64($element['#id'], Settings::getHashSalt() . \Drupal::service('private_key')->get());
    $attribute = new Attribute([
      'data-contextual-id' => $element['#id'],
      'data-contextual-token' => $token,
      'data-drupal-ajax-container' => '',
    ]);
    $element['#markup'] = new FormattableMarkup('<div@attributes></div>', ['@attributes' => $attribute]);

    return $element;
  }

}
$image_style = $this->getImageStyleMock($image_effect_id$image_effect['getPrivateKey', 'getHashSalt']);
    $image_style->expects($this->any())
      ->method('getPrivateKey')
      ->willReturn($private_key);
    $image_style->expects($this->any())
      ->method('getHashSalt')
      ->willReturn($hash_salt);

    // Assert the extension has been added to the URI before creating the token.     $this->assertEquals($image_style->getPathToken('public://test.jpeg.png')$image_style->getPathToken('public://test.jpeg'));
    $this->assertEquals(substr(Crypt::hmacBase64($image_style->id() . ':' . 'public://test.jpeg.png', $private_key . $hash_salt), 0, 8)$image_style->getPathToken('public://test.jpeg'));
    $this->assertNotEquals(substr(Crypt::hmacBase64($image_style->id() . ':' . 'public://test.jpeg', $private_key . $hash_salt), 0, 8)$image_style->getPathToken('public://test.jpeg'));

    // Image style that doesn't change the extension.     $image_effect_id = $this->randomMachineName();
    $image_effect = $this->getMockBuilder('\Drupal\image\ImageEffectBase')
      ->setConstructorArgs([[]$image_effect_id[]$logger])
      ->getMock();
    $image_effect->expects($this->any())
      ->method('getDerivativeExtension')
      ->will($this->returnArgument(0));

    
if ($file->getOwnerId() != \Drupal::currentUser()->id()) {
                  $force_default = TRUE;
                  break;
                }
                // Since file ownership can't be determined for anonymous users,                 // they are not allowed to reuse temporary files at all. But                 // they do need to be able to reuse their own files from earlier                 // submissions of the same form, so to allow that, check for the                 // token added by $this->processManagedFile().                 elseif (\Drupal::currentUser()->isAnonymous()) {
                  $token = NestedArray::getValue($form_state->getUserInput()array_merge($element['#parents']['file_' . $file->id(), 'fid_token']));
                  $file_hmac = Crypt::hmacBase64('file-' . $file->id(), \Drupal::service('private_key')->get() . Settings::getHashSalt());
                  if ($token === NULL || !hash_equals($file_hmac$token)) {
                    $force_default = TRUE;
                    break;
                  }
                }
              }
            }
          }
          if ($force_default) {
            $fids = [];
          }
        }
    // does not contain only the entity label.     $fields = $view->displayHandlers->get('entity_reference_1')->getOption('fields');
    $fields['type']['exclude'] = FALSE;
    $view->displayHandlers->get('entity_reference_1')->setOption('fields', $fields);
    $view->save();

    // Prepare the selection settings key needed by the entity reference     // autocomplete route.     $target_type = 'node';
    $selection_handler = 'views';
    $selection_settings = $this->handlerSettings;
    $selection_settings_key = Crypt::hmacBase64(serialize($selection_settings) . $target_type . $selection_handler, Settings::getHashSalt());
    \Drupal::keyValue('entity_autocomplete')->set($selection_settings_key$selection_settings);

    $result = Json::decode($this->drupalGet('entity_reference_autocomplete/' . $target_type . '/' . $selection_handler . '/' . $selection_settings_key['query' => ['q' => 't']]));

    $expected = [
      0 => [
        'value' => $this->nodes[1]->bundle() . ': ' . $this->nodes[1]->label() . ' (' . $this->nodes[1]->id() . ')',
        'label' => '<span class="views-field views-field-type"><span class="field-content">' . $this->nodes[1]->bundle() . '</span></span>: <span class="views-field views-field-title"><span class="field-content">' . Html::escape($this->nodes[1]->label()) . '</span></span>',
      ],
      1 => [
        'value' => $this->nodes[2]->bundle() . ': ' . $this->nodes[2]->label() . ' (' . $this->nodes[2]->id() . ')',
        
/** * Creates a contextual ID token. * * @param string $id * The contextual ID to create a token for. * * @return string * The contextual ID token. */
  protected function createContextualIdToken($id) {
    return Crypt::hmacBase64($id, Settings::getHashSalt() . $this->container->get('private_key')->get());
  }

}
    $request_time_difference = time() - REQUEST_TIME;
    if (empty($this->failed)) {
      // If we have valid data about release history XML servers that we have       // failed to fetch from on previous attempts, load that.       $this->failed = $this->tempStore->get('fetch_failures');
    }

    $max_fetch_attempts = $this->updateSettings->get('fetch.max_attempts');

    $success = FALSE;
    $available = [];
    $site_key = Crypt::hmacBase64($base_url$this->privateKey->get());
    $fetch_url_base = $this->updateFetcher->getFetchBaseUrl($project);
    $project_name = $project['name'];

    if (empty($this->failed[$fetch_url_base]) || $this->failed[$fetch_url_base] < $max_fetch_attempts) {
      $data = $this->updateFetcher->fetchProjectData($project$site_key);
    }
    if (!empty($data)) {
      $available = $this->parseXml($data);
      // @todo Purge release data we don't need. See       // https://www.drupal.org/node/238950.       if (!empty($available)) {
        
sort($allowed_media_type_ids);
    $opener_parameters = $this->getOpenerParameters();
    ksort($opener_parameters);
    $hash = implode(':', [
      $this->getOpenerId(),
      implode(':', $allowed_media_type_ids),
      $this->getSelectedTypeId(),
      $this->getAvailableSlots(),
      serialize($opener_parameters),
    ]);

    return Crypt::hmacBase64($hash, \Drupal::service('private_key')->get() . Settings::getHashSalt());
  }

  /** * Validate a hash for the state object. * * @param string $hash * The hash to validate. * * @return string * The hashed parameters. */
  
$entity_reference_controller->handleAutocomplete($request$this->entityType, 'default', $selection_settings_key);

      $this->fail('Non-existent selection settings key throws an exception.');
    }
    catch (AccessDeniedHttpException $e) {
      // Expected exception; just continue testing.     }

    try {
      // Generate a valid hash key but store a modified settings array.       $selection_settings = [];
      $selection_settings_key = Crypt::hmacBase64(serialize($selection_settings) . $this->entityType . 'default', Settings::getHashSalt());

      $selection_settings[$this->randomMachineName()] = $this->randomString();
      \Drupal::keyValue('entity_autocomplete')->set($selection_settings_key$selection_settings);

      $entity_reference_controller->handleAutocomplete($request$this->entityType, 'default', $selection_settings_key);
    }
    catch (AccessDeniedHttpException $e) {
      $this->assertSame('Invalid selection settings key.', $e->getMessage());
    }

  }

  

  public function getFullPath($name, &$directory = NULL, &$directory_mtime = NULL) {
    if (!isset($directory)) {
      $directory = $this->getContainingDirectoryFullPath($name);
    }
    if (!isset($directory_mtime)) {
      $directory_mtime = file_exists($directory) ? filemtime($directory) : 0;
    }
    return $directory . '/' . Crypt::hmacBase64($name$this->secret . $directory_mtime) . '.php';
  }

  /** * {@inheritdoc} */
  public function delete($name) {
    $path = $this->getContainingDirectoryFullPath($name);
    if (file_exists($path)) {
      return $this->unlink($path);
    }
    return FALSE;
  }
public function handleAutocomplete(Request $request$target_type$selection_handler$selection_settings_key) {
    $matches = [];
    // Get the typed string from the URL, if it exists.     if ($input = $request->query->get('q')) {
      $tag_list = Tags::explode($input);
      $typed_string = !empty($tag_list) ? mb_strtolower(array_pop($tag_list)) : '';

      // Selection settings are passed in as a hashed key of a serialized array       // stored in the key/value store.       $selection_settings = $this->keyValue->get($selection_settings_key, FALSE);
      if ($selection_settings !== FALSE) {
        $selection_settings_hash = Crypt::hmacBase64(serialize($selection_settings) . $target_type . $selection_handler, Settings::getHashSalt());
        if (!hash_equals($selection_settings_hash$selection_settings_key)) {
          // Disallow access when the selection settings hash does not match the           // passed-in key.           throw new AccessDeniedHttpException('Invalid selection settings key.');
        }
      }
      else {
        // Disallow access when the selection settings key is not found in the         // key/value store.         throw new AccessDeniedHttpException();
      }

      
Home | Imprint | This part of the site doesn't use cookies.