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?
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
.
Not my answer, exactly, but having read the kerfuffle over your last question as well about MD5 vs. SHA, try this article, it could be what you're after.
My solution:
function unique_md5() {
mt_srand(microtime(true)*100000 + memory_get_usage(true));
return md5(uniqid(mt_rand(), true));
}
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.