一段PHP中使用的可逆算法
今天在项目中涉及到cookie内容的加密,看了老半天,发现php中有个mcrypt合适我的要求。下面附上一段代码
//encrypt/decrypt
function crypt_text($str,$key,$method = “encrypt”) {
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
if ($method == “encrypt”) {
$text = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $str, MCRYPT_MODE_ECB, $iv);
} else {
$text = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $str, MCRYPT_MODE_ECB, $iv);
}
return $text;
}
使用方法:
<?
$str = “I’m Silence”; //要加密的字符串
$key = “some private string”; //密钥
$encrypt_str = crypt_text($str,$key,”encrypt”); //得到加密后的结果
$decrypt_str = crypt_text($encrypt_str,$key,”decrypt”); //把加密后的字串解密
echo $encrypt_str.”\r\n”;
echo $decrypt_str.”\r\n”;
?>