欢迎来到无限飞翔,在这里,你会找到许多有趣的技术 : )

加解密:一套加解密函数对【PHP】

PHP编程 lbbniu 2377℃

平时需要对传递到客户端的数据进行简单加密,然后数据到服务器端的时候进行解密,今天推荐一对这样的函数:passport_encrypt($txt, $key);passport_decrypt($txt, $encrypt_key);passport_key($txt, $encrypt_key)

<?php

//加密函数

function passport_encrypt($txt, $key) {

srand((double)microtime() * 1000000);

$encrypt_key = md5(rand(0, 32000));

$ctr = 0;

$tmp = '';

for($i = 0;$i < strlen($txt); $i++) {

$ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;

$tmp .= $encrypt_key[$ctr].($txt[$i] ^ $encrypt_key[$ctr++]);

}

return base64_encode(passport_key($tmp, $key));

}

//解密函数

function passport_decrypt($txt, $key) {

$txt = passport_key(base64_decode($txt), $key);

$tmp = '';

for($i = 0;$i < strlen($txt); $i++) {

$md5 = $txt[$i];

$tmp .= $txt[++$i] ^ $md5;

}

return $tmp;

}

//获取自定义 的key

function passport_key($txt, $encrypt_key) {

$encrypt_key = md5($encrypt_key);

$ctr = 0;

$tmp = '';

for($i = 0; $i < strlen($txt); $i++) {

$ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;

$tmp .= $txt[$i] ^ $encrypt_key[$ctr++];

}

return $tmp;

}

//一个demo样例子

$array = array(

"a" => "1",

"b" => "2",

"c" => "3",

"d" => "4"

);

//serialize产生一个可存储的值,返回一个字符串,unserialize还原

$txt = serialize($array);

$key = 'testkey';

$encrypt = passport_encrypt($txt,$key);

$decrypt = passport_decrypt($encrypt,$key);

$decryptArray = unserialize($decrypt);

echo $txt.'<br><hr>';

echo $encrypt.'<br><hr>';

echo $decrypt.'<br><hr>';

echo $decryptArray.'<br><hr>';

?>

//输出的内容为:

a:4:{s:1:"a";s:1:"1";s:1:"b";s:1:"2";s:1:"c";s:1:"3";s:1:"d";s:1:"4";}


C2pTOgs6XTsELgMjDDoGOFVuUSADZQ0hAW0Kc1FrAjFQagR1VWFbJVQ+DCwBN1RqUGsFdAFkDCAFaVEoUGoHNAsxUyILPF0jBG4DIww6BjhVblEgA2cNIQFtCnNRawIxUGoEdVVjWyVUPgwsATdUalBrBXQBYgwgBWlRKFBqBzQLMVMiCzpdIwRuAy0=


a:4:{s:1:"a";s:1:"1";s:1:"b";s:1:"2";s:1:"c";s:1:"3";s:1:"d";s:1:"4";}


array(4) { ["a"]=> string(1) "1" ["b"]=> string(1) "2" ["c"]=> string(1) "3" ["d"]=> string(1) "4" }

转载请注明:无限飞翔 » 加解密:一套加解密函数对【PHP】

喜欢 (0)or分享 (0)