From 87faed258b07828b307b9a0d901faf9ee139aa1c Mon Sep 17 00:00:00 2001 From: kongmulianhua <1014015565@qq.com> Date: Wed, 21 Oct 2020 14:04:44 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=8C=E6=88=90AES=E5=8A=A0=E8=A7=A3?= =?UTF-8?q?=E5=AF=86=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/AES.php | 4 +- src/classes/AES.php | 94 ++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 95 insertions(+), 3 deletions(-) diff --git a/src/AES.php b/src/AES.php index 998b1a5..08d2dce 100644 --- a/src/AES.php +++ b/src/AES.php @@ -4,9 +4,9 @@ namespace encrypt; interface AES { - public function password(string $password): AES; + public function password(string $password): AES; public function encrypt(string $data): string; - public function decrypt(string $data): string; + public function decrypt(string $data, string $iv): string; } diff --git a/src/classes/AES.php b/src/classes/AES.php index 4a995d3..cabbe95 100644 --- a/src/classes/AES.php +++ b/src/classes/AES.php @@ -2,7 +2,99 @@ namespace encrypt\classes; +/** + * AES加密解密类 + * Class AES + * @package encrypt\classes + */ class AES implements \encrypt\AES { - + /** + * 加密方式 + * @var string + */ + private $method = 'AES-128-CBC'; + + /** + * options选项 + * @var int + */ + private $options = 0; + + /** + * 加密key + * @var string + */ + private $password = ''; + + /** + * 向量 + * @var string + */ + private $iv = ''; + + /** + * 设置key + * @param string $password + * @return \encrypt\AES + */ + public function password(string $password): \encrypt\AES { + $this->password = $password; + return $this; + } + + /** + * 设置加密方式 + * @param string $method + * @return $this + */ + public function method(string $method) { + $this->method = $method; + return $this; + } + + /** + * 设置options选项 + * @param string $options + * @return $this + */ + public function options(string $options) { + $this->options = $options; + return $this; + } + + /** + * 加密数据 + * @param string $data + * @return string + */ + public function encrypt(string $data): string { + if (!$this->password) { + return ''; + } + $ivlength = openssl_cipher_iv_length($this->method); + $this->iv = openssl_random_pseudo_bytes($ivlength); + $encdata = openssl_encrypt($data, $this->method, $this->password, $this->options, $this->iv); + return $encdata; + } + + /** + * 解密数据 + * @param string $data + * @param string $iv + * @return string + */ + public function decrypt(string $data,string $iv): string { + $decdata = openssl_decrypt($data, $this->method, $this->password, $this->options, $iv); + return $decdata; + } + + /** + * 解密向量 + * @return mixed + */ + public function iv() { + return $this->iv; + } + }