generate id session / cookie secure php

0

I'm setting up a login system for my projects. So far I understand that if you usually use sessions, preferably.

article says that it is a good practice to use session ids that are at least 128 bits in size and with 64 bits of entropy, to make id guessing difficult.

Does anyone have any tips for generating an id with these characteristics?

It seems to be only a randon from 0 to 340.282.366.920.938.463.463.374.607.431.768.211.456 (or something nearby)

I think it's easier to work with an alphanumeric string, right? (with unns 26 digits)

    
asked by anonymous 12.10.2017 / 02:01

2 answers

3

Do not use mt_rand , time , rand , lcg_value , or uniquid . These features MAY generate a unique, but not unpredictable, number. Some become pathetic, to predict the time spent just looking at the clock, this is not unpredictable.

Use something that is a CSPRNG, a cryptographically secure pseudo-random generator, you have it in PHP 7:

random_bytes($Quantidade_De_Bytes);

So you can do:

$random = random_bytes(32);

$id = unpack('H*', $random)[1];
echo $id

random_bytes is a CSPRNG, it is secure. Specifying 32 bytes is equivalent to 256 bits.

Do not need hashing ? SHA-3 , BLAKE2 , SHA-2 , SHA-1 , MD5 , {put the name here} ? No. The hashes were made to be indistinguishable from a random string. So if it has a truly random string, or a secure pseudo-random, it is already equivalent to a hash.

The default session system in PHP 7.1 already uses random_bytes , you can configure your strength using session.sid_length and session.sid_bits_per_character .

    
12.10.2017 / 14:32
1

Here is a code that can generate a 512-bit identifier (128 characters in base16 or hexadecimal), from the user name, system local time, process identifier, and a random number:

<?php

$user = 'FULANO';
$pid = getmypid();
$now = new DateTime();
$rnd = mt_rand( 100000000, 999999999 );

$str = $now->format('Y.m.d.H.i.s.u.z.v.U').$user.$pid.$rnd;

$id_session = hash('sha512', $str );

echo $id_session;

?>
    
12.10.2017 / 04:39