1 | <?php |
||
19 | trait CryptTrait |
||
20 | { |
||
21 | /** |
||
22 | * @var string|Key|null |
||
23 | */ |
||
24 | protected $encryptionKey; |
||
25 | |||
26 | /** |
||
27 | * Encrypt data with encryptionKey. |
||
28 | * |
||
29 | * @param string $unencryptedData |
||
30 | * |
||
31 | * @throws LogicException |
||
32 | * |
||
33 | * @return string |
||
34 | */ |
||
35 | 30 | protected function encrypt($unencryptedData) |
|
36 | { |
||
37 | try { |
||
38 | 30 | if ($this->encryptionKey instanceof Key) { |
|
39 | return Crypto::encrypt($unencryptedData, $this->encryptionKey); |
||
40 | } |
||
41 | |||
42 | 30 | if (is_string($this->encryptionKey)) { |
|
43 | 30 | return Crypto::encryptWithPassword($unencryptedData, $this->encryptionKey); |
|
44 | } |
||
45 | |||
46 | throw new LogicException('Encryption key not set when attempting to encrypt'); |
||
47 | } catch (Exception $e) { |
||
48 | throw new LogicException($e->getMessage(), 0, $e); |
||
49 | } |
||
50 | } |
||
51 | |||
52 | /** |
||
53 | * Decrypt data with encryptionKey. |
||
54 | * |
||
55 | * @param string $encryptedData |
||
56 | * |
||
57 | * @throws LogicException |
||
58 | * |
||
59 | * @return string |
||
60 | */ |
||
61 | 29 | protected function decrypt($encryptedData) |
|
62 | { |
||
63 | try { |
||
64 | 29 | if ($this->encryptionKey instanceof Key) { |
|
65 | return Crypto::decrypt($encryptedData, $this->encryptionKey); |
||
66 | } |
||
67 | |||
68 | 29 | if (is_string($this->encryptionKey)) { |
|
69 | 29 | return Crypto::decryptWithPassword($encryptedData, $this->encryptionKey); |
|
70 | } |
||
71 | |||
72 | throw new LogicException('Encryption key not set when attempting to decrypt'); |
||
73 | 2 | } catch (Exception $e) { |
|
74 | 2 | throw new LogicException($e->getMessage(), 0, $e); |
|
75 | } |
||
76 | } |
||
77 | |||
78 | /** |
||
79 | * Set the encryption key |
||
80 | * |
||
81 | * @param string|Key $key |
||
82 | */ |
||
83 | 81 | public function setEncryptionKey($key = null) |
|
87 | } |
||
88 |