-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathToken.php
93 lines (80 loc) · 2.39 KB
/
Token.php
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
<?php
/**
* @package Flextype Components
*
* @author Sergey Romanenko <[email protected]>
* @link http://components.flextype.org
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Flextype\Component\Token;
use Flextype\Component\Session\Session;
class Token
{
/**
* Key name for token storage
*
* @var string
*/
public static $token_name = 'security_token';
/**
* Generate and store a unique token which can be used to help prevent
* [CSRF](http://wikipedia.org/wiki/Cross_Site_Request_Forgery) attacks.
*
* $token = Token::generate();
*
* You can insert this token into your forms as a hidden field:
*
* <input type="hidden" name="csrf" value="<?php echo Token::generate(); ?>">
*
* This provides a basic, but effective, method of preventing CSRF attacks.
*
* @param bool $new force a new token to be generated?. Default is false
* @return string
*/
public static function generate(bool $new = false) : string
{
// Get the current token
$token = Session::get(Token::$token_name);
// Create a new unique token
if ($new === true OR ! $token) {
// Generate a new unique token
$token = sha1(uniqid(mt_rand(), true));
// Store the new token
Session::set(Token::$token_name, $token);
}
// Return token
return $token;
}
/**
* Check that the given token matches the currently stored security token.
*
* if (Token::check($token)) {
* // Pass
* }
*
* @param string $token token to check
* @return bool
*/
public static function check(string $token) : bool
{
return Token::slowEquals(Token::generate(), $token);
}
/**
* Compare two hashes in a time-invariant manner.
* Prevents cryptographic side-channel attacks (timing attacks, specifically)
*
* @param string $a cryptographic hash
* @param string $b cryptographic hash
* @return bool
*/
public static function slowEquals(string $a, string $b) : bool
{
$diff = strlen($a) ^ strlen($b);
for($i = 0; $i < strlen($a) AND $i < strlen($b); $i++) {
$diff |= ord($a[$i]) ^ ord($b[$i]);
}
return $diff === 0;
}
}