1 /**2 * DES加密类3 * User: gaowei4 * Date: 2017/12/125 * Time: 19:236 */
7 classDesEncrypt {8 private $key = "";9 private $iv = "";10
11 /**12 * 构造,传递二个已经进行base64_encode的KEY与IV13 *14 * @param string $key15 * @param string $iv16 */
17 function __construct ($key, $iv)18 {19 if (empty($key) || empty($iv)) {20 echo 'key and iv is not valid';21 exit();22 }23 $this->key = $key;24 $this->iv = $iv;//825 //$this->iv = $iv.'00000000000';//16
26
27 }28
29 /**30 * @title 加密31 * @author gaowei32 * @date 2017/12/1833 * @param string $value 要传的参数34 * @ //OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING //AES-128-ECB|AES-256-CBC|BF-CBC35 * @return json36 **/
37 public function encrypt ($value) {38
39 //参考地址:https://stackoverflow.com/questions/41181905/php-mcrypt-encrypt-to-openssl-encrypt-and-openssl-zero-padding-problems#
40 $value = $this->PaddingPKCS7($value);41 $key = base64_decode($this->key);42 $iv = base64_decode($this->iv);43 //AES-128-ECB|不能用 AES-256-CBC|16 AES-128-CBC|16 BF-CBC|8 aes-128-gcm|需要加$tag DES-EDE3-CBC|8
44 $cipher = "DES-EDE3-CBC";45 if (in_array($cipher,openssl_get_cipher_methods())) {46 //$ivlen = openssl_cipher_iv_length($cipher);47 // $iv = openssl_random_pseudo_bytes($ivlen);
48 $result = openssl_encrypt($value, $cipher, $key, OPENSSL_SSLV23_PADDING, $iv);49 //$result = base64_encode($result); //为3的时间要用50 //store $cipher, $iv, and $tag for decryption later
51 /*$original_plaintext = openssl_decrypt($result, $cipher, $key, OPENSSL_SSLV23_PADDING, $iv);52 echo $original_plaintext."\n";*/
53 }54 return $result;55
56 }57 /**58 * @title 解密59 * @author gaowei60 * @date 2017/12/1861 * @param string $value 要传的参数62 * @return json63 **/
64 public function decrypt ($value) {65 $key = base64_decode($this->key);66 $iv = base64_decode($this->iv);67 $decrypted = openssl_decrypt($value, 'DES-EDE3-CBC', $key, OPENSSL_SSLV23_PADDING, $iv);68 $ret = $this->UnPaddingPKCS7($decrypted);69 return $ret;70 }71
72 private function PaddingPKCS7 ($data) {73 //$block_size = mcrypt_get_block_size('tripledes', 'cbc');//获取长度74 //$block_size = openssl_cipher_iv_length('tripledes', 'cbc');//获取长度
75 $block_size = 8;76 $padding_char = $block_size - (strlen($data) % $block_size);77 $data .= str_repeat(chr($padding_char), $padding_char);78 return $data;79 }80 private function UnPaddingPKCS7($text) {81 $pad = ord($text{strlen($text) - 1});82 if ($pad > strlen($text)) {83 return false;84 }85 if (strspn($text, chr($pad), strlen($text) - $pad) != $pad) {86 return false;87 }88 return substr($text, 0, - 1 * $pad);89 }90 }

被折叠的 条评论
为什么被折叠?



