Skip to content

Instantly share code, notes, and snippets.

@nojacko
Last active December 10, 2015 11:38
Show Gist options
  • Save nojacko/4429248 to your computer and use it in GitHub Desktop.
Save nojacko/4429248 to your computer and use it in GitHub Desktop.
Testing PHP Random Salt Generataion
# Testing PHP Random Salt Generation
## Functions for generating salt
### mt_rand()
```
function mtSalt ($length = 22)
{
mt_srand();
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789./';
$salt = '';
for ($i = 0; $i < $length; $i++) {
$salt .= $chars[mt_rand(0, 63)];
}
return $salt;
}
```
### mcrypt_create_iv()
Simplified from https://github.com/ircmaxell/password_compat/blob/master/lib/password.php#L88
```
function ivSalt ($length = 22)
{
$salt = mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
$salt = str_replace('+', '.', base64_encode($salt));
return substr($salt, 0, $length);
}
```
## The Test
* Created 18,000,000+ 22 character hashes with each function.
* Imported hashes into a MySQL database table.
* Counted disinct values: SELECT COUNT(DISTINCT(salt)) FROM `<TABLE>`;
## Results
* mt_rand() distinct values: 13,268,133 of 18,453,000 (72%)
* mcrypt_create_iv() distinct values: 18,453,000 of 18,453,000 (100%)
## Conclusion
mt_rand() doesn't give great entropy for salts, mcrypt_create_iv() does. Entropy is good.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment