AES介绍

高级加密标准(英语:Advanced Encryption Standard,缩写:AES),在密码学中又称Rijndael加密法,是美国联邦政府采用的一种区块加密标准。

这个标准用来替代原先的DES,已经被多方分析且广为全世界所使用。 经过五年的甄选流程,高级加密标准由美国国家标准与技术研究院(NIST)于2001年11月26日发布于FIPS PUB 197,并在2002年5月26日成为有效的标准。 2006年,高级加密标准已然成为对称密钥加密中最流行的算法之一。

class AES
{
    public $method = '';
    public $key = '';
    public $iv = '';

    public function __construct(string $method, string $key, string $iv)
    {
        if (!in_array($method, openssl_get_cipher_methods())) {
            throw new \Exception($method . ' encryption method is not support.');
        }
        $this->method = $method;
        $this->key = $key;
        $this->iv = $iv;
    }

    //AES加密
    public function aesEncryption(string $data): string
    {
        $result = openssl_encrypt($data, $this->method, $this->key, OPENSSL_RAW_DATA, $this->iv);
        return base64_encode($result);
    }

    //AES解密
    public function aesDecryption(string $data): string
    {
        return openssl_decrypt(base64_decode($data), $this->method, $this->key, OPENSSL_RAW_DATA, $this->iv);
    }
}

$config = [
    'AES-128-CBC1', //method加密方式  # AES-256-CBC等
    'helloworld', //key加密key
    md5(time() . uniqid(), true), //iv保证偏移量为16位
];

try{
    $obj = new AES(...$config);
    echo $encryptionResult = $obj->aesEncryption('Jack') . PHP_EOL;
    echo $decryptionResult = $obj->aesDecryption($encryptionResult) . PHP_EOL;
}catch (\Exception $e){
    exit($e->getMessage().PHP_EOL);
}