A class that provides simple interface for decryptable encryption.
- PHP:
^7.1 || ^8.0
composer require mpyw/easycrypt
The default cipher method is aes256
(aes-256-cbc
).
<?php
use Mpyw\EasyCrypt\Cryptor;
$cryptor = new Cryptor;
$secretData = '[Secret Data]';
$password = '[Password]';
$encrypted = $cryptor->encrypt($secretData, $password);
$decrypted = $cryptor->decrypt($encrypted, $password); // String on success, false on failure.
var_dump($secretData === $decrypted); // bool(true)
It throws DecryptionFailedException
instead of returning false.
$decrypted = $cryptor->mustDecrypt($encrypted, $password);
You can use FixedPasswordCryptor
instead of raw Cryptor
.
This is useful when we use a fixed password from an application config.
<?php
use Mpyw\EasyCrypt\FixedPasswordCryptor;
$cryptor = new FixedPasswordCryptor('[Password]');
$secretData = '[Secret Data]';
$encrypted = $cryptor->encrypt($secretData);
$decrypted = $cryptor->decrypt($encrypted); // String on success, false on failure.
var_dump($secretData === $decrypted); // bool(true)
If you need to use AEAD suites that adopt CTR mode, it is recommended to provide truly unique counter value.
use Mpyw\EasyCrypt\IvGenerator\IvGeneratorInterface;
class Counter implements IvGeneratorInterface
{
protected \PDO $pdo;
public function __construct(\PDO $pdo)
{
$this->pdo = $pdo;
}
public function generate(int $length): string
{
$this->pdo->exec('INSERT INTO counters()');
return $this->pdo->lastInsertId();
}
}
<?php
use Mpyw\EasyCrypt\Cryptor;
$cryptor = new Cryptor('aes-256-gcm', new Counter(new \PDO(...)));