您好,欢迎访问一九零五行业门户网

PHP中DES加解密的代码示例

本篇文章给大家带来的内容是关于php中des加解密的代码示例,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
test.php测试文件
<?phprequire_once('des.php');$des = new des();$data['a'] = 'a';$data['b'] = 'b';$conf = ['appkey'=>'abcdefghijklmnopqrstuvwx','secretcode'=>'abcdefgh'];$encode = $des->encode($data, $conf);print_r($encode);echo "<br>";$decode = $des->decode($encode,$conf);print_r($decode);?>
des.php
<?phprequire_once('tripledes.php');class des { public static function encode($data, $configkey) { $tripledes = new tripledes(); if (is_array($data)) { $data = json_encode($data); } return $tripledes->encode($data, $configkey["appkey"], $configkey["secretcode"]); } public static function decode($data, $configkey) { $tripledes = new tripledes(); return $tripledes->decode($data, $configkey["appkey"], $configkey["secretcode"]); } public static function encodearr($data, $configkey) { $data = json_encode($data); return self::encode($data, $configkey); } public static function decodearr($data, $configkey) { $res = self::decode($data, $configkey); return json_decode($res,true); }}
tripledes.php
<?phpclass tripledes { public static function genivparameter() { return mcrypt_create_iv(mcrypt_get_iv_size(mcrypt_tripledes, mcrypt_mode_cbc), mcrypt_rand); } private static function pkcs5pad($text, $blocksize) { $pad = $blocksize - (strlen($text) % $blocksize); // in php, strlen returns the bytes of $text return $text . str_repeat(chr($pad), $pad); } private static function pkcs5unpad($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); } public static function encrypttext($plain_text, $key, $iv) { $padded = tripledes::pkcs5pad($plain_text, mcrypt_get_block_size(mcrypt_tripledes, mcrypt_mode_cbc)); return mcrypt_encrypt(mcrypt_tripledes, $key, $padded, mcrypt_mode_cbc, $iv); } public static function decrypttext($cipher_text, $key, $iv) { if(function_exists('mcrypt_decrypt')){ $plain_text = mcrypt_decrypt(mcrypt_tripledes, $key, $cipher_text, mcrypt_mode_cbc, $iv); }else{ $plain_text = openssl_decrypt($cipher_text, 'des-ede3-cbc',$key, openssl_no_padding,$iv); } return tripledes::pkcs5unpad($plain_text); } public static function decode($cipher_text, $key, $iv) { $cipher_text = base64_decode($cipher_text); $cipher_text = tripledes::decrypttext($cipher_text, $key, $iv); return $cipher_text; } public static function encode($cipher_text, $key, $iv) { $cipher_text = tripledes::encrypttext($cipher_text, $key, $iv); return base64_encode($cipher_text); }}
【推荐课程:php视频教程】
以上就是php中des加解密的代码示例的详细内容。
其它类似信息

推荐信息