How to generate a random, long salt for use in hashing?

爱⌒轻易说出口 提交于 2019-11-28 23:27:15

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.


If the mcrypt extension is available you could simply use mcrypt_create_iv(size, source) to create a salt.

$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.

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.

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.

C.

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;
}

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 microtime and rand, for example, but you might go to even greater lengths to ensure that your salt is unique.

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.

EDIT: Substitute rand() for mt_rand(). As Michael noted, it's better than rand.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!