-
Notifications
You must be signed in to change notification settings - Fork 18
/
Symmetric.php
99 lines (84 loc) · 2.2 KB
/
Symmetric.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
94
95
96
97
98
99
<?php
namespace Emarref\Jwt\Encryption;
use Emarref\Jwt\Algorithm;
/**
* @property Algorithm\SymmetricInterface $algorithm
*/
class Symmetric extends AbstractEncryption implements EncryptionInterface
{
/**
* @var string
*/
private $secret;
/**
* @param Algorithm\SymmetricInterface $algorithm
*/
public function __construct(Algorithm\SymmetricInterface $algorithm)
{
parent::__construct($algorithm);
}
/**
* @return string
*/
public function getSecret()
{
return $this->secret;
}
/**
* @param string $secret
* @return $this
*/
public function setSecret($secret)
{
$this->secret = $secret;
return $this;
}
/**
* @param string $value
* @return string
*/
public function encrypt($value)
{
return $this->algorithm->compute($value);
}
/**
* @param string $value
* @param string $signature
* @return boolean
*/
public function verify($value, $signature)
{
$computedValue = $this->algorithm->compute($value);
return $this->timingSafeEquals($signature, $computedValue);
}
/**
* A timing safe equals comparison.
*
* @see http://blog.ircmaxell.com/2014/11/its-all-about-time.html
*
* @param string $safe The internal (safe) value to be checked
* @param string $user The user submitted (unsafe) value
*
* @return boolean True if the two strings are identical.
*/
public function timingSafeEquals($safe, $user)
{
if (function_exists('hash_equals')) {
return hash_equals($user, $safe);
}
$safeLen = strlen($safe);
$userLen = strlen($user);
/*
* In general, it's not possible to prevent length leaks. So it's OK to leak the length.
* @see http://security.stackexchange.com/questions/49849/timing-safe-string-comparison-avoiding-length-leak
*/
if ($userLen != $safeLen) {
return false;
}
$result = 0;
for ($i = 0; $i < $userLen; $i++) {
$result |= (ord($safe[$i]) ^ ord($user[$i]));
}
return $result === 0;
}
}