🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
友情链接:https://www.tytrock.com/topics/216 完整例子 ``` class Aes { private $paddingChar = "\0"; private $key; private $iv; private $option = OPENSSL_ZERO_PADDING; private $method = 'aes-128-cbc'; /** * Aescrypt constructor. * * @param $key * @param $iv */ public function __construct($key = 'nnNdYE3MftWm5gWn', $iv = '9mXW4f4fvgSFG0bt') { $this->key = $key; $this->iv = $iv; } /** * @param string $content * * @return string * @desc aes-128加密 */ public function encrypt($content) { $strLength = strlen($content); $content .= str_repeat($this->paddingChar, 16 - $strLength % 16); $data = openssl_encrypt($content, $this->method, $this->key, $this->option, $this->iv); if (false === $data) { echo openssl_error_string(); exit; } return $data; } /** * @param string $encryptData * * @return string * @desc aes-128解密 */ public function decrypt($encryptData) { $data = openssl_decrypt($encryptData, $this->method, $this->key, $this->option, $this->iv); return substr($data, 0, strpos($data, $this->paddingChar)); } } ``` php openssl_decrypt 的 OPENSSL_ZERO_PADDING默认会补零到16位 `AES-128:需要提供 16 位的密钥 key` `AES-192:需要提供 24 位的密钥 key` `AES-256:需要提供 32 位的密钥 key` ``` public static function opensslDecrypt($data = '') { if (empty($data) || !is_string($data)) { return $data; } $method = 'aes-128-cbc'; $privateKey = 'F79JF2tNdHLW4bid'; //todo $iv = 'bk4h1mv84RCOdyn2'; //todo $res = ''; if ($decrypt = openssl_decrypt($data, $method, $privateKey, OPENSSL_ZERO_PADDING, $iv)) { $res = rtrim($decrypt, "\0"); // 或者 $cleaned = strval(str_replace("\0", "", $password)); } return $res; } ``` 前端 cryptojs:下载地址 https://code.google.com/archive/p/crypto-js/downloads cryptojs:文档说明 https://cryptojs.gitbook.io/docs/ cryptojs:在线调试工具 https://tool.oschina.net/encrypt ``` <!-- 加密js--> <script src="__STATIC__/common/js/crypto/rollups/aes.js"></script> <script src="__STATIC__/common/js/crypto/components/pad-zeropadding.js"></script> /** * 加密 */ function doEncrypt(data) { if (data == '' || data == undefined) { return data; } let key = CryptoJS.enc.Latin1.parse('F79JF2tNdHLW4bid'); let iv = CryptoJS.enc.Latin1.parse('bk4h1mv84RCOdyn2'); //加密 return CryptoJS.AES.encrypt(data, key, {iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.ZeroPadding}); } ```