要生成有效的盐,必须知道哪种算法将使用该盐。通常您可以使用该函数base64_encode()
从二进制盐中检索标准字符,它将生成一个具有以下字母的字符串:
base64 encoding alphabeth: +/0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
如果 Silex 将盐用于 BCrypt 哈希算法,它将期望具有以下字母的盐,请注意“。” 而不是“+”:
BCrypt hash alphabet: ./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
我认为最好测试一下允许使用哪些字符,或者找出将使用哪种算法,否则您迟早会生成无效的盐。使用该函数生成 BCrypt 盐的示例mcrypt_create_iv()
如下所示:
/**
* Generates a random salt for using with the BCrypt algorithm.
* @param int $length Number of characters the string should have.
* @return string A random salt.
*/
function sto_generateRandomSalt($length = 22)
{
if (!defined('MCRYPT_DEV_URANDOM')) die('The MCRYPT_DEV_URANDOM source is required (PHP 5.3).');
// Generate random bytes, using the operating system's random source.
// Since PHP 5.3 this also uses the random source on a Windows server.
// Unlike /dev/random, the /dev/urandom does not block the server, if
// there is not enough entropy available.
$randomBinaryString = mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
// BCrypt expects nearly the same alphabet as base64_encode returns,
// but instead of the '+' characters it accepts '.' characters.
// BCrypt alphabet: ./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
$randomEncodedString = str_replace('+', '.', base64_encode($randomBinaryString));
return substr($randomEncodedString, 0, $length);
}