暗号化を使用しないのはなぜですか?
有効期限を安全に処理できるようにするこの質問に触発されました。
$time = time() + 90;
$key = "a private password";
echo "Expiration time = {$time}<br/>";
$code = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $time, MCRYPT_MODE_CBC, md5(md5($key))));
echo "Sharable encrypted code = {$code}<br/>";
(.......そしてしばらくすると、$code が戻ってきます)
$time = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($code), MCRYPT_MODE_CBC, md5(md5($key))), "\0");
echo "Decoded time is {$time}...";
if ($time < time()) {
echo "Code has expired<br/>";
} else {
echo "Code is OK<br/>";
}
これは出力します:
Expiration time = 1347312816
Sharable encrypted code = ioVqtqZud+iexObaGBF418i0gHKHshjsy+mj+oM4KMw=
Decoded time is 1347312816...Code is OK
このような方法では、次の 2 つの関数が必要です。
// returns a code valid $duration seconds
function createKey($duration) {
$key = "a private password";
$time = time() + $duration;
$code = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $time, MCRYPT_MODE_CBC, md5(md5($key))));
return $code;
}
// returns true if code is still valid
function checkKey($code)
{
$key = "a private password";
$time = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($code), MCRYPT_MODE_CBC, md5(md5($key))), "\0");
return ($time >= time());
}