不久前,我选择了一个安全的随机生成器,它应该非常适合您的 cookie 验证令牌(会话 ID);
function TokenGenerator($Length)
{
$CharPool = '0123456789';
$CharPool .= 'abcdefghijklmnopqrstuvwxyz';
$CharPool .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$RandomNumber = function($Minimum, $Maximum)
{
# Find the range of the maximum and minimum allowed output
$Range = $Maximum - $Minimum;
# If the range is less than 0 forget the rest and return the minimum allowed number as a 'random' bit
if($Range < 0)
{
return $Minimum;
}
# Calculate the logarithm for $Range variable
$Logarithm = (int) log($Range, 2)+1;
$ByteLength = (int) ($Logarithm-1/8)+1;
$BitF = (int) (1 << $Logarithm)-1;
do
{
# Get some random binary bytes
$RndBinBytes = openssl_random_pseudo_bytes($ByteLength);
# Converts the binary to hexadecimal
$HexBytes = bin2hex($RndBinBytes);
# Convert the hexadecimal bytes to decimal
$Random = hexdec($HexBytes);
# Use the AND operator to discard the unneeded bits
$Random = $Random & $BitF;
}
while($Random >= $Range);
# Return the random number found by the sub function to the main function
return $Minimum + $Random;
};
# Initialise the RandChars variable
$RandChars = '';
$LengthOfPool = strlen($CharPool);
for ($Counter = 0; $Counter < $Length; $Counter +=1)
{
$RandNum = $RandomNumber(0, $LengthOfPool);
# Pick from the pool of chars
$RandChar = $CharPool[$RandNum];
# Append the random char to the token to be returned at the end
$RandChars .= $RandChar;
}
return $RandChars;
}
要为您的 cookie 计划添加另一层安全性,您可以加密 cookie 的内容以确保 cookie 首先不被篡改,当我设置 cookie 时,我使用此类;
class CookieMonster
{
private $CookieKey = 'SecurePassword';
public function SetCookie($Name, $Data, $Expire=31536000)
{
if($Data == '')
{
return FALSE;
}
if($Name == '')
{
return FALSE;
}
if($Key == '')
{
return FALSE;
}
return setcookie($Name, $this->Encrypt($Data, $this->CookieKey), $Expire);
}
public function DeleteCookie($Name)
{
if(isset($_COOKIE[$Name]))
{
return setcookie($Name, '', 1);
}
}
public function ReadCookie($Name)
{
if(isset($_COOKIE[$Name]))
{
return $this->Decrypt($_COOKIE[$Name], $this->CookieKey);
}else{
return FALSE;
}
}
public function Encrypt($Data, $Key)
{
return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, sha1($Key), $Data, MCRYPT_MODE_CBC, md5(sha1($Key))));
}
public function Decrypt($Data, $Key)
{
return rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, sha1($Key), base64_decode($Data), MCRYPT_MODE_CBC, md5(sha1($Key))), "\0");
}
}