我想在cookie(用户名,电子邮件地址等)中保存数据,但我不是用户可以轻松阅读或修改它.我需要能够读回数据.我怎么能用PHP 5.2做到这一点?
它将用于“welcome back bob”类功能.它不是持久性或会话存储的替代品.
解决方法
我们在项目中使用mcrypt来实现加密.以下是基于互联网上的内容的代码示例:
<?PHP class MyProjCrypt { private $td; private $iv; private $ks; private $salt; private $encStr; private $decStr; /** * The constructor initializes the cryptography library * @param $salt string The encryption key * @return void */ function __construct($salt) { $this->td = mcrypt_module_open('rijndael-256','','ofb',''); // algorithm $this->ks = mcrypt_enc_get_key_size($this->td); // key size needed for the algorithm $this->salt = substr(md5($salt),$this->ks); } /** * Generates a hex string of $src * @param $src string String to be encrypted * @return void */ function encrypt($src) { srand(( double) microtime() * 1000000); //for sake of MCRYPT_RAND $this->iv = mcrypt_create_iv($this->ks,MCRYPT_RAND); mcrypt_generic_init($this->td,$this->salt,$this->iv); $tmpStr = mcrypt_generic($this->td,$src); mcrypt_generic_deinit($this->td); mcrypt_module_close($this->td); //convert the encrypted binary string to hex //$this->iv is needed to decrypt the string later. It has a fixed length and can easily //be seperated out from the encrypted String $this->encStr = bin2hex($this->iv.$tmpStr); } /** * Decrypts a hex string * @param $src string String to be decrypted * @return void */ function decrypt($src) { //convert the hex string to binary $corrected = preg_replace("[^0-9a-fA-F]","",$src); $binenc = pack("H".strlen($corrected),$corrected); //retrieve the iv from the encrypted string $this->iv = substr($binenc,$this->ks); //retrieve the encrypted string alone(minus iv) $binstr = substr($binenc,$this->ks); /* Initialize encryption module for decryption */ mcrypt_generic_init($this->td,$this->iv); /* Decrypt encrypted string */ $decrypted = mdecrypt_generic($this->td,$binstr); /* Terminate decryption handle and close module */ mcrypt_generic_deinit($this->td); mcrypt_module_close($this->td); $this->decStr = trim($decrypted); } }