<?php /** * Desc: Aes 加解密 php7.1+ * Class: Aes * Package: app\common\lib * User: manzb * Date: 2018/10/18 17:30 */ namespace app\common\lib; class Aes { private $iv = ''; private $key = ''; private $method = ''; function __construct () { $aes = config('admin.aes'); /** * $aes 内容 'aes' => [ 'key' => '309w4wb42104160d2g6806lv1ki60f98',//aes加密盐 'method' => 'AES-256-CBC',//加密方式 'hex' => '00000000000000000000000000000000',//生成iv参数用,貌似是为了安卓ios相互兼容取的这个值 ],
可根据每个用户账号的不同设置不同的key字段 */ $this->method = $aes['method']; $this->key = hash('sha256', $aes['key'], true); $this->iv = $this->hex2iv($aes['hex']); } /** * 加密 * @param $str * @return string */ public function encrypt ($str) { $encrypt = openssl_encrypt($str, $this->method, $this->key, OPENSSL_RAW_DATA, $this->iv); return base64_encode($encrypt); } /** * 解密 * @param $str * @return string */ public function decrypt ($str) { $decrypted = openssl_decrypt(base64_decode($str), $this->method, $this->key, OPENSSL_RAW_DATA, $this->iv); return $decrypted; } /** * 生成iv参数 * @param $hex * @return string */ private function hex2iv ($hex) { $iv = ''; for ($i = 0; $i < strlen($hex) - 1; $i += 2) { $iv .= chr(hexdec($hex[$i] . $hex[$i + 1])); } return $iv; } }