3 namespace Wallabag\CoreBundle\Helper
;
5 use Defuse\Crypto\Crypto
;
6 use Defuse\Crypto\Exception\WrongKeyOrModifiedCiphertextException
;
8 use Psr\Log\LoggerInterface
;
11 * This is a proxy to crypt and decrypt password used by SiteCredential entity.
12 * BTW, It might be re-use for sth else.
17 private $encryptionKey;
19 public function __construct($encryptionKeyPath, LoggerInterface
$logger)
21 $this->logger
= $logger;
23 if (!file_exists($encryptionKeyPath)) {
24 $key = Key
::createNewRandomKey();
26 file_put_contents($encryptionKeyPath, $key->saveToAsciiSafeString());
27 chmod($encryptionKeyPath, 0600);
30 $this->encryptionKey
= file_get_contents($encryptionKeyPath);
34 * Ensure the given value will be crypted.
36 * @param string $secretValue Secret valye to crypt
40 public function crypt($secretValue)
42 $this->logger
->debug('Crypto: crypting value: ' . $this->mask($secretValue));
44 return Crypto
::encrypt($secretValue, $this->loadKey());
48 * Ensure the given crypted value will be decrypted.
50 * @param string $cryptedValue The value to be decrypted
54 public function decrypt($cryptedValue)
56 $this->logger
->debug('Crypto: decrypting value: ' . $this->mask($cryptedValue));
59 return Crypto
::decrypt($cryptedValue, $this->loadKey());
60 } catch (WrongKeyOrModifiedCiphertextException
$e) {
61 throw new \
RuntimeException('Decrypt fail: ' . $e->getMessage());
66 * Load the private key.
70 private function loadKey()
72 return Key
::loadFromAsciiSafeString($this->encryptionKey
);
76 * Keep first and last character and put some stars in between.
78 * @param string $value Value to mask
82 private function mask($value)
84 return strlen($value) > 0 ? $value[0] . '*****' . $value[strlen($value) - 1] : 'Empty value';