function encrypt($value, $key = '1234567891234567') { $length = mb_strlen($key, '8bit'); if (!$length === 16) { return false; } $seeds = '0123456789abcdefghijklmnopqrstuvwxyz'; $length = 16; $iv = substr(str_shuffle(str_repeat($seeds, $length)), 0, $length); $value = \openssl_encrypt(serialize($value), 'AES-128-CBC', $key, 0, $iv); if ($value === false) { return false; } $iv = base64_encode($iv); $mac = hash_hmac('sha256', $iv.$value, $key); $json = json_encode(compact('iv', 'value', 'mac')); if (! is_string($json)) { return false; } return base64_encode($json); } function decrypt($payload, $key = '1234567891234567') { $length = mb_strlen($key, '8bit'); if (!$length === 16) { return false; } $payload = json_decode(base64_decode($payload), true); if (! $payload || ! is_array($payload) || ! isset($payload['iv']) || ! isset($payload['value']) || ! isset($payload['mac'])) { return false; } $seeds = '0123456789abcdefghijklmnopqrstuvwxyz'; $length = 16; $bytes = substr(str_shuffle(str_repeat($seeds, $length)), 0, $length); $hash = hash_hmac('sha256', $payload['iv'].$payload['value'], $key); $calcMac = hash_hmac('sha256', $hash, $bytes, true); if (! hash_equals(hash_hmac('sha256', $payload['mac'], $bytes, true), $calcMac)) { return false; } $iv = base64_decode($payload['iv']); $decrypted = \openssl_decrypt($payload['value'], 'AES-128-CBC', $key, 0, $iv); if ($decrypted === false) { return false; } return unserialize($decrypted); } $str = '123456'; $encrypt = encrypt($str); $decrypt = decrypt($encrypt); var_dump($decrypt); 随便写的,看着用吧