Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 611
Tony Stark Avatar asked Feb 10 '10 08:02

Tony Stark


People also ask

How long should the salt be hashing?

Make sure the salt isn't too short and do not simply use the usernames of the password as your salts. Salts should be 32 characters or longer in length.

How is password salt generated?

A cryptographic salt is made up of random bits added to each password instance before its hashing. Salts create unique passwords even in the instance of two users choosing the same passwords. Salts help us mitigate hash table attacks by forcing attackers to re-compute them using the salts for each user.

Is hash salt random?

When using both hashing and salting, even if two users choose the same password, salting adds random characters to each password when the users enter them. As a result, completely different hashes are generated to prevent the passwords and accounts from being compromised.

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


2 Answers

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.

like image 123
VolkerK Avatar answered Oct 16 '22 18:10

VolkerK


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.

like image 24
symcbean Avatar answered Oct 16 '22 16:10

symcbean