AES-128-ECB php兼容高低版本
短信预约 -IT技能 免费直播动态提醒
class Aes { public static function encrypt($plain, $key) { if (trim($key) == '') { return false; } $key = self::_sha1prng($key); if(version_compare(PHP_VERSION,'7.1','>=')){ $iv = ''; $encrypted = openssl_encrypt($plain, 'AES-128-ECB', $key, OPENSSL_RAW_DATA, $iv); }else{ $plain = strval($plain); $block_size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB); $padded_data = self::_pkcs5_pad($plain, $block_size); $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB); $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND); $encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $padded_data, MCRYPT_MODE_ECB, $iv); } return base64_encode($encrypted); } public static function decrypt($cipher, $key) { if ( ! is_string($cipher) || trim($key) == '') { return false; } $key = self::_sha1prng($key); $decoded = base64_decode($cipher); if ($decoded){ if(version_compare(PHP_VERSION,'7.1','>=')){ $iv = ''; return openssl_decrypt($decoded, 'AES-128-ECB', $key, OPENSSL_RAW_DATA, $iv); }else{ $block_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB); $iv = mcrypt_create_iv($block_size, MCRYPT_RAND); $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $decoded, MCRYPT_MODE_ECB, $iv); return self::_pkcs5_unpad($decrypted); } } return false; } private static function _sha1prng($key) { return substr(openssl_digest(openssl_digest($key, 'sha1', true), 'sha1', true), 0, 16); } private static function _pkcs5_pad($text, $block_size) { $pad = $block_size - (strlen($text) % $block_size); return $text . str_repeat(chr($pad), $pad); } private static function _pkcs5_unpad($text) { $end = substr($text, -1); $last = ord($end); $len = strlen($text) - $last; if (substr($text, $len) == str_repeat($end, $last)) { return substr($text, 0, $len); } return false; }}//使用方法:$keyStr = 'sdez';$aes = new Aes();$str = '{"openCode":"a9ae-8394-49bb","phone":"9988","name":"test","type":"2"}';$chgstr = $aes->encrypt($str,$keyStr);echo $chgstr;echo PHP_EOL;$rstr = $aes->decrypt($chgstr,$keyStr);echo $rstr;
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341