1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192 |
- <?php
- namespace huoIdentify\controller;
- class AES {
-
- private $key;
-
- private $cipher;
-
- private $ivlen;
-
- public function __construct($key, $cipher = 'aes-128-gcm', $ivlen = 12) {
- $this->cipher = $cipher;
- $this->ivlen = $ivlen;
- $this->key = hex2bin($key);
- }
-
- public function decrypt($cipherText, callable $callback = null) {
- if (!is_null($callback)) {
- $cipherText = call_user_func($callback, $cipherText);
- } else {
-
- $cipherText = base64_decode($cipherText);
- }
- $iv = substr($cipherText, 0, $this->ivlen);
- $data = substr($cipherText, $this->ivlen, strlen($cipherText) - 16 - $this->ivlen);
- $tag = substr($cipherText, strlen($cipherText) - 16);
- return openssl_decrypt($data, $this->cipher, $this->key, OPENSSL_RAW_DATA, $iv, $tag);
- }
-
- public function encrypt($plainText, callable $callback = null) {
- $iv = openssl_random_pseudo_bytes($this->ivlen, $result);
- if (!$result) {
- throw new \Exception('random bytes error');
- }
- $tag = null;
- $data = openssl_encrypt($plainText, $this->cipher, $this->key, OPENSSL_RAW_DATA, $iv, $tag);
- $data = $iv.$data.$tag;
- if (!is_null($callback)) {
- return call_user_func($callback, $data);
- }
-
- return rtrim(base64_encode($data), "=");
- }
- }
|