1
|
<?php
|
2
|
|
3
|
namespace Illuminate\Encryption;
|
4
|
|
5
|
use Illuminate\Contracts\Encryption\DecryptException;
|
6
|
|
7
|
abstract class BaseEncrypter
|
8
|
{
|
9
|
/**
|
10
|
* The encryption key.
|
11
|
*
|
12
|
* @var string
|
13
|
*/
|
14
|
protected $key;
|
15
|
|
16
|
/**
|
17
|
* Create a MAC for the given value.
|
18
|
*
|
19
|
* @param string $iv
|
20
|
* @param string $value
|
21
|
* @return string
|
22
|
*/
|
23
|
protected function hash($iv, $value)
|
24
|
{
|
25
|
return hash_hmac('sha256', $iv.$value, $this->key);
|
26
|
}
|
27
|
|
28
|
/**
|
29
|
* Get the JSON array from the given payload.
|
30
|
*
|
31
|
* @param string $payload
|
32
|
* @return array
|
33
|
*
|
34
|
* @throws \Illuminate\Contracts\Encryption\DecryptException
|
35
|
*/
|
36
|
protected function getJsonPayload($payload)
|
37
|
{
|
38
|
$payload = json_decode(base64_decode($payload), true);
|
39
|
|
40
|
// If the payload is not valid JSON or does not have the proper keys set we will
|
41
|
// assume it is invalid and bail out of the routine since we will not be able
|
42
|
// to decrypt the given value. We'll also check the MAC for this encryption.
|
43
|
if (! $payload || $this->invalidPayload($payload)) {
|
44
|
throw new DecryptException('The payload is invalid.');
|
45
|
}
|
46
|
|
47
|
if (! $this->validMac($payload)) {
|
48
|
throw new DecryptException('The MAC is invalid.');
|
49
|
}
|
50
|
|
51
|
return $payload;
|
52
|
}
|
53
|
|
54
|
/**
|
55
|
* Verify that the encryption payload is valid.
|
56
|
*
|
57
|
* @param array|mixed $data
|
58
|
* @return bool
|
59
|
*/
|
60
|
protected function invalidPayload($data)
|
61
|
{
|
62
|
return ! is_array($data) || ! isset($data['iv']) || ! isset($data['value']) || ! isset($data['mac']);
|
63
|
}
|
64
|
|
65
|
/**
|
66
|
* Determine if the MAC for the given payload is valid.
|
67
|
*
|
68
|
* @param array $payload
|
69
|
* @return bool
|
70
|
*
|
71
|
* @throws \RuntimeException
|
72
|
*/
|
73
|
protected function validMac(array $payload)
|
74
|
{
|
75
|
$bytes = random_bytes(16);
|
76
|
|
77
|
$calcMac = hash_hmac('sha256', $this->hash($payload['iv'], $payload['value']), $bytes, true);
|
78
|
|
79
|
return hash_equals(hash_hmac('sha256', $payload['mac'], $bytes, true), $calcMac);
|
80
|
}
|
81
|
}
|