blob: 3e2338086c4b81ff069d36a0291e64a98ea7d406 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
<?php
class CSRF
{
/** @var string */
const HMAC_ALGORITHM = 'sha1';
/**
* Ensure that a CSRF token is valid for a given action.
*
* @param string $token
* @param string $action
* @return bool
*/
public static function verify($token = '', $action = null)
{
if (!is_string($token) || !is_string($action)) {
return false;
}
$known = self::generate($action);
return hash_equals($known, $token);
}
/**
* Generate a CSRF token for a given action.
*
* @param string $action
* @throws InvalidArgumentException
* @return string
*/
public static function generate($action = null)
{
if (!is_string($action)) {
throw InvalidArgumentException('A valid action must be defined.');
}
return hash_hmac(self::HMAC_ALGORITHM, $action, self::getKey());
}
/**
* Get HMAC key.
*
* @return string
*/
public static function getKey()
{
return session_id();
}
}
|