Using mcrypt to get a password salt. Execution time is fast on local apache server, but very slow on web host

StackOverflow https://stackoverflow.com/questions/18238982

Question

$salt=bin2hex(mcrypt_create_iv(64, MCRYPT_DEV_RANDOM));

This is my current setup for creating a password salt. I noticed that when I uploaded my register page to the web host it took about 1 minute for the page to execute, while on my local apache server it was instant. I narrowed down the problem to this line of code. Are you aware of any execution time problems with this function or is there a better way to get a salt string (128 length)?

Was it helpful?

Solution

The problem lies with the MCRYPT_DEV_RANDOM parameter, reading from this will block the server until enough entrophy is available. Instead you should use:

$binarySalt = mcrypt_create_iv(64, MCRYPT_DEV_URANDOM);

Reading from URANDOM is the better choice for generating a salt, it is initially feeded from RANDOM but it doesn't block if there is not enough entrophy available. This also prevents, that somebody can drain the servers' entrophy pool by using your function.

Depending on what hash function you use, the bin2hex() function is not optimal, because the alphabet of the resulting string is limited. You should allow all characters that are accepted by the hash function.

Since PHP now has its own api to generate BCrypt hashes, i would recommend to use this function directly password_hash(), it does take care of the creation of a safe salt. There is also a compatibility pack for earlier PHP versions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top