PHP的AES加密

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); }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章