forked from absolute-quantum/DoctrineEncryptBundle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHaliteEncryptor.php
63 lines (52 loc) · 1.46 KB
/
HaliteEncryptor.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
<?php
namespace Ambta\DoctrineEncryptBundle\Encryptors;
use \ParagonIE\Halite\HiddenString;
use \ParagonIE\Halite\KeyFactory;
/**
* Class for encrypting and decrypting with the halite library
*
* @author Michael de Groot <[email protected]>
*/
class HaliteEncryptor implements EncryptorInterface
{
private $encryptionKey;
private $keyFile;
/**
* {@inheritdoc}
*/
public function __construct(string $keyFile)
{
$this->keyFile = $keyFile;
}
/**
* {@inheritdoc}
*/
public function encrypt($data)
{
return \ParagonIE\Halite\Symmetric\Crypto::encrypt(new HiddenString($data), $this->getKey());
}
/**
* {@inheritdoc}
*/
public function decrypt($data)
{
$data = \ParagonIE\Halite\Symmetric\Crypto::decrypt($data, $this->getKey());
if ($data instanceof HiddenString)
{
$data = $data->getString();
}
return $data;
}
private function getKey()
{
if ($this->encryptionKey === null) {
try {
$this->encryptionKey = \ParagonIE\Halite\KeyFactory::loadEncryptionKey($this->keyFile);
} catch (\ParagonIE\Halite\Alerts\CannotPerformOperation $e) {
$this->encryptionKey = KeyFactory::generateEncryptionKey();
\ParagonIE\Halite\KeyFactory::save($this->encryptionKey, $this->keyFile);
}
}
return $this->encryptionKey;
}
}