php aes加解密,mcrypt_encrypt 和openssl_encrypt
php7.1以下版本使用
/* * mcrypt_encrypt 加密 * php7.1开始被丢弃 可以使用openssl_encrypt * */ function aes_encrypt($content){ $privateKey = "abcdef1234567890"; $iv = "helloworld123456"; $content = $this->pkcs7_pad($content); //支持openssl_decrypt 解密, $encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128,$privateKey,$content,MCRYPT_MODE_CBC,$iv); $based_encrypted = base64_encode($encrypted); return $based_encrypted; }
/* * mcrypt_encrypt 解密 * */ function aes_decrypt($content){ $privateKey = "abcdef1234567890"; $iv = "helloworld123456"; $content = base64_decode($content); $encrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128,$privateKey,$content,MCRYPT_MODE_CBC,$iv); return $encrypted; } function pkcs7_pad($str){ $len = mb_strlen($str, '8bit'); $c = 16 - ($len % 16); $str .= str_repeat(chr($c), $c); return $str; }
php7.1开始被丢弃 可以使用openssl_encrypt
/** * 解密字符串 * @param string $data 字符串 * @param string $key 加密key * @return string */ function decryptWithOpenssl($data,$key,$iv){ return openssl_decrypt(base64_decode($data),"AES-128-CBC",$key,OPENSSL_RAW_DATA,$iv); } /** * 加密字符串 * 参考网站: https://segmentfault.com/q/1010000009624263 * @param string $data 字符串 * @param string $key 加密key * @return string */ function encryptWithOpenssl($data,$key,$iv){ return base64_encode(openssl_encrypt($data,"AES-128-CBC",$key,OPENSSL_RAW_DATA,$iv)); }
使用方法
header("Content-type:text/html; charset=utf-8"); $privateKey = "abcdef1234567890"; $iv = "helloworld123456"; echo "<pre>"; $content = '章节内容加密测试121212ksjflkdjslfsdjfljs章节内容测试end'; $aesencrypt = aes_encrypt($content); echo "aes_encrypt加密:".($aesencrypt); echo "<br/>"; $encrypt_openssl = aes_decrypt($aesencrypt); echo "aes_decrypt解密:".($encrypt_openssl); echo "<br/>"; $encrypt_openssl = decryptWithOpenssl($aesencrypt,$privateKey,$iv); echo "openssl_encrypt解密:".($encrypt_openssl); echo "<br/>"; $encrypt_openssl = encryptWithOpenssl($content,$privateKey,$iv); echo "openssl_encrypt加密:".($encrypt_openssl); echo "<br/>"; $decrypt_openssl =decryptWithOpenssl($encrypt_openssl,$privateKey,$iv); echo "openssl_encrypt解密:".($decrypt_openssl); echo "<br/>"; $decrypt_openssl = aes_decrypt($encrypt_openssl); echo "aes_decrypt解密:".($decrypt_openssl); echo "<br/>";