php 如何生成用于散列的随机长盐?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2235434/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to generate a random, long salt for use in hashing?
提问by Tony Stark
What is a way in PHP to make a random, variable length salt for use in hashing? Let's say I want to make a 16-character long salt - how would I do it?
PHP 中有什么方法可以制作用于散列的随机可变长度盐?假设我想制作一个 16 个字符的长盐 - 我该怎么做?
回答by VolkerK
edit: the mcrypt extension has been deprecated.
For new projects take a look at
random_bytes ( int $length )
and the sodium(as of php 7.2 core-)extension.
编辑:mcrypt 扩展已被弃用。对于新项目,请查看
random_bytes ( int $length )
和sodium(as of php 7.2 core-) extension。
If the mcrypt extensionis available you could simply use mcrypt_create_iv(size, source)to create a salt.
如果mcrypt 扩展可用,您可以简单地使用mcrypt_create_iv(size, source)创建盐。
$iv = mcrypt_create_iv(16, MCRYPT_DEV_URANDOM);
var_dump($iv);
Since each byte of the "string" can be in the range between 0-255 you need a binary-safe function to save/retrieve it.
由于“字符串”的每个字节都可以在 0-255 之间的范围内,因此您需要一个二进制安全函数来保存/检索它。
回答by symcbean
depending on your OS, something like:
取决于您的操作系统,例如:
$fh=fopen('/dev/urandom','rb');
$salt=fgets($fh,16);
fclose($fh);
Do read up on the behaviour of random and urandom.
请仔细阅读 random 和 urandom 的行为。
While others have correctly pointed out that there some issues with md5 and repeated hashing, for passwords (i.e. relatively short strings) brute force attacks take the same amount of time regardless of how sophisticated the hashing algorithm is.
虽然其他人已经正确地指出 md5 和重复散列存在一些问题,但对于密码(即相对较短的字符串),无论散列算法有多复杂,暴力攻击都会花费相同的时间。
C.
C。
回答by Raksmey
Here is I found a function to generate random string:
这是我找到了一个生成随机字符串的函数:
/* random string */
function rand_string( $length ) {
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$size = strlen( $chars );
for( $i = 0; $i < $length; $i++ ) {
$str .= $chars[ rand( 0, $size - 1 ) ];
}
return $str;
}
回答by Johannes Gorset
There are two prerequisites for a good salt: It must be long, and it must be random. There are many ways to accomplish this. You could use a combination of microtimeand rand, for example, but you might go to even greater lengths to ensure that your salt is unique.
一个好的盐有两个先决条件:一定要长,一定要随机。有很多方法可以实现这一点。你可以使用的组合microtime并rand,例如,但你可能会去更大的长度,以确保您的盐是独一无二的。
While the chance of a collision is neglible, keep in mind that hashing your salt with MD5 or other collision-prone algorithms will reduce the chance that your salt is unique for no reason.
虽然碰撞的可能性可以忽略不计,但请记住,使用 MD5 或其他容易发生冲突的算法散列您的 salt 将减少您的 salt 无缘无故独特的可能性。
EDIT: Substitute rand()for mt_rand(). As Michael noted, it's better than rand.
编辑:替代rand()的mt_rand()。正如迈克尔所指出的,它比rand.

