Tony Stark
Tony Stark

Reputation: 25558

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

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?

Upvotes: 14

Views: 28036

Answers (4)

VolkerK
VolkerK

Reputation: 96159

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.

Upvotes: 60

Raksmey
Raksmey

Reputation: 49

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

Upvotes: 2

Johannes Gorset
Johannes Gorset

Reputation: 8785

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.

Upvotes: 0

symcbean
symcbean

Reputation: 48367

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.

Upvotes: 3

Related Questions