工具类: <?php class DesEncrypt { private $key = ""; private $iv = ""; /** * 构造,传递二个已经进行base64_encode的KEY与IV * * @param string $key * @param string $iv */ function __construct ($key, $iv) { if (empty($key) || empty($iv)) { echo 'key and iv is not valid'; exit(); } $this->key = $key; $this->iv = $iv; } /** * @title 加密 * @author gaowei * @date 2017/12/18 * @param string $value 要传的参数 * @ //OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING //AES-128-ECB|AES-256-CBC|BF-CBC * @return json * */ public function encrypt ($value) { $value = $this->PaddingPKCS7($value); $key = $this->key; $iv = $this->iv; //AES-128-ECB|不能用 AES-256-CBC|16 AES-128-CBC|16 BF-CBC|8 aes-128-gcm|需要加$tag DES-EDE3-CBC|8 $cipher = "DES-EDE3-CBC"; if (in_array($cipher, openssl_get_cipher_methods())) { $result = openssl_encrypt($value, $cipher, $key, OPENSSL_SSLV23_PADDING, $iv); } return $result; } /** * @title 解密 * @author gaowei * @date 2017/12/18 * @param string $value 要传的参数 * @return json * */ public function decrypt ($value) { $key = $this->key; $iv = $this->iv; $decrypted = openssl_decrypt($value, 'DES-EDE3-CBC', $key, OPENSSL_SSLV23_PADDING, $iv); $ret = $this->UnPaddingPKCS7($decrypted); return $ret; } private function PaddingPKCS7 ($data) { $block_size = 8; $padding_char = $block_size - (strlen($data) % $block_size); $data .= str_repeat(chr($padding_char), $padding_char); return $data; } private function UnPaddingPKCS7($text) { $pad = ord($text{strlen($text) - 1}); if ($pad > strlen($text)) { return false; } if (strspn($text, chr($pad), strlen($text) - $pad) != $pad) { return false; } return substr($text, 0, - 1 * $pad); } } 使用方法: include "DesEncrypt.php"; $str = '{"type":"test","user_id":"000"}'; $des = new DesEncrypt("1234567890","01234567"); echo $des->encrypt($str); echo "<br>"; echo $des->decrypt("VsewcF6I94fHLZhrFYohB52GgASfdDeQJLZnr3C2AeE="); PHP技术交流QQ群:422137578 除非注明,文章均为 PHP二次开发 原创,转载请注明本文地址:http://www.php2.cc/article-2691-1.html |