You are here

public static function Csp::calculateHash in Content-Security-Policy 8

Calculate the Base64 encoded hash of a script.

Parameters

string $data: The source data to hash.

string $algorithm: The hash algorithm to use. Supported values are defined in \Drupal\csp\Csp::HASH_ALGORITHMS.

Return value

string The hash value in the format <hash-algorithm>-<base64-value>

2 calls to Csp::calculateHash()
CspTest::testHash in tests/src/Unit/CspTest.php
Test calculating hash values.
CspTest::testInvalidHashAlgo in tests/src/Unit/CspTest.php
Test specifying an invalid hash algorithm.

File

src/Csp.php, line 137

Class

Csp
A CSP Header.

Namespace

Drupal\csp

Code

public static function calculateHash($data, $algorithm = 'sha256') {
  if (!in_array($algorithm, self::HASH_ALGORITHMS)) {
    throw new \InvalidArgumentException("Specified hash algorithm is not supported");
  }
  return $algorithm . '-' . base64_encode(hash($algorithm, $data, TRUE));
}