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?
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.
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.
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.
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With