最新赞助活动温馨提示:自愿赞助服务器费用,学生和没有工作的整站资源免费下载!
头像

PHP加密解密实例分析_php技巧

来源:http://erdangjiade.com/topic/131246.html 你好,世界。 2017-10-04 21:03浏览(68)

本文实例讲述了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程序设计有所帮助。

评论0
头像

友情提示:垃圾评论一律封号 加我微信:826096331拉你进VIP群学习群

1 2