mpyw/easycrypt

一个提供可解密加密简单接口的类。

v4.1.1 2021-07-01 08:39 UTC

This package is auto-updated.

Last update: 2024-09-13 07:57:35 UTC


README

一个提供可解密加密 简单 接口的类。

要求

  • PHP: ^7.1 || ^8.0

安装

composer require mpyw/easycrypt

使用方法

基本

默认加密方法是 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)

解密失败时抛出 DecryptionFailedException

它抛出 DecryptionFailedException 而不是返回 false。

$decrypted = $cryptor->mustDecrypt($encrypted, $password);

使用固定密码

您可以使用 FixedPasswordCryptor 而不是原始的 Cryptor。这在我们需要从应用程序配置中获取固定密码时很有用。

<?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)

使用 AEAD (带有关联数据的认证加密) 套件

如果您需要使用采用 CTR 模式的 AEAD 套件,建议提供真正唯一的计数器值。

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(...)));