Completed
Branch 09branch (a008bb)
by Anton
03:16
created

Encrypter::random()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 10
nc 4
nop 2
dl 0
loc 19
rs 8.8571
c 0
b 0
f 0
1
<?php
2
/**
3
 * Spiral Framework.
4
 *
5
 * @license   MIT
6
 * @author    Anton Titov (Wolfy-J)
7
 */
8
9
namespace Spiral\Encrypter;
10
11
use Defuse\Crypto\Crypto;
12
use Defuse\Crypto\Exception\CryptoException;
13
use Defuse\Crypto\Key;
14
use Spiral\Core\Container\InjectableInterface;
15
use Spiral\Encrypter\Exceptions\DecryptException;
16
use Spiral\Encrypter\Exceptions\EncryptException;
17
18
/**
19
 * Default implementation of spiral encrypter. Sugary implementation at top of defuse/php-encryption
20
 *
21
 * @see  https://github.com/defuse/php-encryption
22
 */
23
class Encrypter implements EncrypterInterface, InjectableInterface
24
{
25
    /**
26
     * Injector is dedicated to outer class since Encrypter is pretty simple.
27
     */
28
    const INJECTOR = EncrypterManager::class;
29
30
    /**
31
     * @var Key
32
     */
33
    private $key = null;
34
35
    /**
36
     * Encrypter constructor.
37
     *
38
     * @param string $key Loads a Key from its encoded form (ANSI).
39
     */
40
    public function __construct(string $key)
41
    {
42
        $this->key = Key::loadFromAsciiSafeString($key);
43
    }
44
45
    /**
46
     * {@inheritdoc}
47
     */
48
    public function withKey(string $key): EncrypterInterface
49
    {
50
        $encrypter = clone $this;
51
        $encrypter->key = Key::loadFromAsciiSafeString($key);
52
53
        return $encrypter;
54
    }
55
56
    /**
57
     * {@inheritdoc}
58
     */
59
    public function getKey(): string
60
    {
61
        return $this->key->saveToAsciiSafeString();
62
    }
63
64
    /**
65
     * {@inheritdoc}
66
     *
67
     * Data encoded using json_encode method, only supported formats are allowed!
68
     */
69
    public function encrypt($data): string
70
    {
71
        $packed = json_encode($data);
72
73
        try {
74
            return base64_encode(Crypto::Encrypt($packed, $this->key));
75
        } catch (CryptoException $e) {
76
            throw new EncryptException($e->getMessage(), $e->getCode(), $e);
77
        }
78
    }
79
80
    /**
81
     * {@inheritdoc}
82
     *
83
     * json_decode with assoc flag set to true
84
     */
85
    public function decrypt(string $payload)
86
    {
87
        try {
88
            $result = Crypto::Decrypt(
89
                base64_decode($payload),
90
                $this->key
91
            );
92
93
            return json_decode($result, true);
94
        } catch (CryptoException $e) {
95
            throw new DecryptException($e->getMessage(), $e->getCode(), $e);
96
        }
97
    }
98
}
99