What is the best way to create a random hash/string?

Viewed 111863

What is the best way of generating a hash for the purpose of storing a session? I am looking for a lightweight, portable solution.

9 Answers

random_bytes() is available as of PHP 7.0 (or use this polyfill for 5.2 through 5.6). It is cryptographically secure (compared to rand() which is not) and can be used in conjunction with bin2hex(), base64_encode(), or any other function that converts binary to a string that's safe for your use case.

As a hexadecimal string

bin2hex() will result in a hexadecimal string that's twice as many characters as the number of random bytes (each hex character represents 4 bits while there are 8 bits in a byte). It will only include characters from abcdef0123456789 and the length will always be an increment of 2 (regex: /^([a-f0-9]{2})*$/).

$random_hex = bin2hex(random_bytes(18));
echo serialize($random_hex);

s:36:"ee438d1d108bd818aa0d525602340e5d7036";

As a base64 string

base64_encode() will result in a string that's about 33% longer than the number of random bytes (each base64 character represents 6 bits while there are 8 bits in a byte). It's length will always be an increment of 4, with = used to pad the end of the string and characters from the following list used to encode the data (excluding whitespace that I added for readability):

abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
0123456789
/+

To take full advantage of the space available, it's best to provide an increment of 3 to random_bytes(). The resulting string will match /^([a-zA-Z\/+=]{4})*$/, although = can only appear at the end as = or == and only when a number that is not an increment of 3 is provided to random_bytes().

$random_base64 = base64_encode(random_bytes(18));
echo serialize($random_base64);

s:24:"ttYDDiGPV5K0MXbcfeqAGniH";

You can use PHP's built-in hashing functions, sha1 and md5. Choose one, not both.

One may think that using both, sha1(md5($pass)) would be a solution. Using both does not make your password more secure, its causes redundant data and does not make much sense.

Take a look at PHP Security Consortium: Password Hashing they give a good article with weaknesses and improving security with hashing.

Nonce stands for "numbers used once". They are used on requests to prevent unauthorized access, they send a secret key and check the key each time your code is used.

You can check out more at PHP NONCE Library from FullThrottle Development

I generally dont manually manage session ids. Ive seen something along these lines recommended for mixing things up a bit before, ive never used myself so i cant attest to it being any better or worse than the default (Note this is for use with autogen not with manual management).

//md5 "emulation" using sha1
ini_set('session.hash_function', 1);
ini_set('session.hash_bits_per_character', 5);
Related