|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/** |
|
4
|
|
|
* Spiral Framework. |
|
5
|
|
|
* |
|
6
|
|
|
* @license MIT |
|
7
|
|
|
* @author Anton Titov (Wolfy-J) |
|
8
|
|
|
*/ |
|
9
|
|
|
|
|
10
|
|
|
declare(strict_types=1); |
|
11
|
|
|
|
|
12
|
|
|
namespace Spiral\Encrypter; |
|
13
|
|
|
|
|
14
|
|
|
use Defuse\Crypto\Exception\CryptoException; |
|
15
|
|
|
use Defuse\Crypto\Key; |
|
16
|
|
|
use Spiral\Core\Container\InjectorInterface; |
|
17
|
|
|
use Spiral\Core\Container\SingletonInterface; |
|
18
|
|
|
use Spiral\Encrypter\Config\EncrypterConfig; |
|
19
|
|
|
use Spiral\Encrypter\Exception\EncrypterException; |
|
20
|
|
|
|
|
21
|
|
|
/** |
|
22
|
|
|
* Only manages encrypter injections (factory). |
|
23
|
|
|
*/ |
|
24
|
|
|
final class EncrypterFactory implements InjectorInterface, EncryptionInterface, SingletonInterface |
|
25
|
|
|
{ |
|
26
|
|
|
/** @var EncrypterConfig */ |
|
27
|
|
|
protected $config = null; |
|
28
|
|
|
|
|
29
|
|
|
/** |
|
30
|
|
|
* @param EncrypterConfig $config |
|
31
|
|
|
*/ |
|
32
|
|
|
public function __construct(EncrypterConfig $config) |
|
33
|
|
|
{ |
|
34
|
|
|
$this->config = $config; |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
|
|
/** |
|
38
|
|
|
* @inheritdoc |
|
39
|
|
|
* @codeCoverageIgnore |
|
40
|
|
|
*/ |
|
41
|
|
|
public function generateKey(): string |
|
42
|
|
|
{ |
|
43
|
|
|
try { |
|
44
|
|
|
return Key::createNewRandomKey()->saveToAsciiSafeString(); |
|
45
|
|
|
} catch (CryptoException $e) { |
|
46
|
|
|
throw new EncrypterException($e->getMessage(), $e->getCode(), $e); |
|
47
|
|
|
} |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
/** |
|
51
|
|
|
* @inheritdoc |
|
52
|
|
|
*/ |
|
53
|
|
|
public function getKey(): string |
|
54
|
|
|
{ |
|
55
|
|
|
try { |
|
56
|
|
|
Key::loadFromAsciiSafeString($this->config->getKey()); |
|
57
|
|
|
} catch (CryptoException $e) { |
|
58
|
|
|
throw new EncrypterException($e->getMessage(), $e->getCode(), $e); |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
return $this->config->getKey(); |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
|
|
/** |
|
65
|
|
|
* @return EncrypterInterface |
|
66
|
|
|
*/ |
|
67
|
|
|
public function getEncrypter(): EncrypterInterface |
|
68
|
|
|
{ |
|
69
|
|
|
return new Encrypter($this->getKey()); |
|
70
|
|
|
} |
|
71
|
|
|
|
|
72
|
|
|
/** |
|
73
|
|
|
* {@inheritdoc} |
|
74
|
|
|
*/ |
|
75
|
|
|
public function createInjection(\ReflectionClass $class, string $context = null) |
|
76
|
|
|
{ |
|
77
|
|
|
return $this->getEncrypter(); |
|
78
|
|
|
} |
|
79
|
|
|
} |
|
80
|
|
|
|