Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating a salt in PHP

What's the best way to generate a cryptographically secure 32 bytes salt in PHP, without depending on libraries seldom included in typical PHP installations?

After some googling I discovered that mt_rand is not considered secure enough, but I haven't found a suggestion for a replacement. One article suggested reading from /dev/random but not only this won't work on windows; it is also very slow.

I want a reasonable balance between security and speed (ie, it shouldn't take 20 seconds to generate 512 bytes, like /dev/random usually does)

like image 655
qster Avatar asked Mar 25 '10 07:03

qster


People also ask

What is a salt PHP?

What is a salt? A cryptographic salt is data which is applied during the hashing process in order to eliminate the possibility of the output being looked up in a list of pre-calculated pairs of hashes and their input, known as a rainbow table.

How do you generate a random salt in Java?

To generate salt bytes in Java, we just need to make sure that we use a secure random number generator. Construct an instance of SecureRandom, create (say) a 20-byte array, and call nextBytes() on that array: Random r = new SecureRandom(); byte[] salt = new byte[20]; r. nextBytes(salt);


1 Answers

This is easier in PHP 7: Just use $salt = random_bytes($numberOfDesiredBytes); to generate a salt.

What do you need a salt for, anyway? If it's for passwords, just use password_hash() and password_verify().

like image 82
Scott Arciszewski Avatar answered Oct 03 '22 05:10

Scott Arciszewski