Crypt.php 2.16 KB
Newer Older
1
2
3
4
5
6
<?php

namespace Drupal\Component\Utility;

/**
 * Utility class for cryptographically-secure string handling routines.
7
8
 *
 * @ingroup utility
9
10
11
12
13
14
 */
class Crypt {

  /**
   * Calculates a base-64 encoded, URL-safe sha-256 hmac.
   *
15
16
17
18
   * @param mixed $data
   *   Scalar value to be validated with the hmac.
   * @param mixed $key
   *   A secret key, this can be any scalar value.
19
20
21
22
23
24
   *
   * @return string
   *   A base-64 encoded sha-256 hmac, with + replaced with -, / with _ and
   *   any = padding characters removed.
   */
  public static function hmacBase64($data, $key) {
25
    // $data and $key being strings here is necessary to avoid empty string
26
    // results of the hash function if they are not scalar values. As this
27
28
29
30
31
32
33
    // function is used in security-critical contexts like token validation it
    // is important that it never returns an empty string.
    if (!is_scalar($data) || !is_scalar($key)) {
      throw new \InvalidArgumentException('Both parameters passed to \Drupal\Component\Utility\Crypt::hmacBase64 must be scalar values.');
    }

    $hmac = base64_encode(hash_hmac('sha256', $data, $key, TRUE));
34
    // Modify the hmac so it's safe to use in URLs.
35
    return str_replace(['+', '/', '='], ['-', '_', ''], $hmac);
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
  }

  /**
   * Calculates a base-64 encoded, URL-safe sha-256 hash.
   *
   * @param string $data
   *   String to be hashed.
   *
   * @return string
   *   A base-64 encoded sha-256 hash, with + replaced with -, / with _ and
   *   any = padding characters removed.
   */
  public static function hashBase64($data) {
    $hash = base64_encode(hash('sha256', $data, TRUE));
    // Modify the hash so it's safe to use in URLs.
51
    return str_replace(['+', '/', '='], ['-', '_', ''], $hash);
52
53
54
  }

  /**
55
   * Returns a URL-safe, base64 encoded string of highly randomized bytes.
56
   *
57
   * @param $count
58
   *   The number of random bytes to fetch and base64 encode.
59
60
   *
   * @return string
61
62
   *   A base-64 encoded string, with + replaced with -, / with _ and any =
   *   padding characters removed.
63
   */
64
  public static function randomBytesBase64($count = 32) {
65
    return str_replace(['+', '/', '='], ['-', '_', ''], base64_encode(random_bytes($count)));
66
67
68
  }

}