PHP的AES加密
阿新 • • 發佈:2018-11-05
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); }