class Aes { public static function encrypt($plain, $key) { if (trim($key) == '') { retu
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;
--结束END--
本文标题: AES-128-ECB php兼容高低版本
本文链接: https://lsjlt.com/news/397674.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0