欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

PHP加密解密实例分析

程序员文章站 2022-05-30 08:14:22
本文实例讲述了php加密解密方法。分享给大家供大家参考,具体如下: //加密 function string2secret($str) { $key =...

本文实例讲述了php加密解密方法。分享给大家供大家参考,具体如下:

//加密
function string2secret($str)
{
 $key = "123";
 $td = mcrypt_module_open(mcrypt_des,'','ecb','');
 $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), mcrypt_rand);
 $ks = mcrypt_enc_get_key_size($td);
 $key = substr(md5($key), 0, $ks);
 mcrypt_generic_init($td, $key, $iv);
 $secret = mcrypt_generic($td, $str);
 mcrypt_generic_deinit($td);
 mcrypt_module_close($td);
 return $secret;
}
//解密
function secret2string($sec)
{
 $key = "123";
 $td = mcrypt_module_open(mcrypt_des,'','ecb','');
 $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), mcrypt_rand);
 $ks = mcrypt_enc_get_key_size($td);
 $key = substr(md5($key), 0, $ks);
 mcrypt_generic_init($td, $key, $iv);
 $string = mdecrypt_generic($td, $sec);
 mcrypt_generic_deinit($td);
 mcrypt_module_close($td);
 return trim($string);
}
echo secret2string(string2secret("11111111111111111"));
//显示结果是11111111111111111
echo '<br>'.string2secret("11111111111111111");
//显示乱码
echo '<br>';
//$string:要加密的字符串 $isencrypt=true:加密 $isencrypt=false:解密
function dencrypt($string, $isencrypt = true, $key = "key_space") {
 if (!isset($string{0}) || !isset($key{0})) {
  return false;
 }
 $dynkey = $isencrypt ? hash('sha1', microtime(true)) : substr($string, 0, 40);
 $fixedkey = hash('sha1', $key);
 $dynkeypart1 = substr($dynkey, 0, 20);
 $dynkeypart2 = substr($dynkey, 20);
 $fixedkeypart1 = substr($fixedkey, 0, 20);
 $fixedkeypart2 = substr($fixedkey, 20);
 $key = hash('sha1', $dynkeypart1 . $fixedkeypart1 . $dynkeypart2 . $fixedkeypart2);
 $string = $isencrypt ? $fixedkeypart1 . $string . $dynkeypart2 : (isset($string{339}) ? gzuncompress(base64_decode(substr($string, 40))) : base64_decode(substr($string, 40)));
 $n = 0;
 $result = '';
 $len = strlen($string);
 for ($n = 0; $n < $len; $n++) {
  $result .= chr(ord($string{$n}) ^ ord($key{$n % 40}));
 }
 return $isencrypt ? $dynkey . str_replace('=', '', base64_encode($n > 299 ? gzcompress($result) : $result)) : substr($result, 20, -20);
}
echo strlen(dencrypt("12345678912345"));

希望本文所述对大家php程序设计有所帮助。