Creating cryptographically secure tokens

To create a 32-character token to access our API, we currently use:

$token = md5(uniqid(mt_rand(), true)); 

I read that this method is not cryptographically secure because it is based on a system clock, and that openssl_random_pseudo_bytes would be a better solution, since it would be harder to predict.

If so, what does the equivalent code look like?

I guess something like this, but I don't know if this is right ...

 $token = md5(openssl_random_pseudo_bytes(32)); 

And what length does it make sense that I have to go to the function?

+47
security php openssl token
Sep 16 '13 at 14:43
source share
4 answers

Here is the correct solution:

 $token = bin2hex(openssl_random_pseudo_bytes(16)); # or in php7 $token = bin2hex(random_bytes(16)); 
+114
Sep 19 '13 at 8:57
source share

If you want to use openssl_random_pseudo_bytes, it is better to use the CrytoLib implementation, this will allow you to generate all the alphanumeric characters by sticking bin2hex around openssl_random_pseudo_bytes, it will just get AF (caps) and numbers.

Replace the path / with / where you put the cryptolib.php file (you can find it on GitHub at: https://github.com/IcyApril/CryptoLib )

 <?php require_once('path/to/cryptolib.php'); $token = CryptoLib::randomString(16); ?> 

Full CryptoLib documentation is available at: https://cryptolib.ju.je/ . It covers many other random methods, cascading encryption and hash generation and validation; but he is there if you need it.

+8
Dec 29 '15 at 0:45
source share

If you have a cryptographically secure random number generator, you do not need to display it on the screen. In fact, you do not want this. Just use

 $token = openssl_random_pseudo_bytes($BYTES,true) 

Where $ BYTES, however, is a lot of bytes of data that you want. MD5 has a 128-bit hash, so 16 bytes will be executed.

As a side note, not one of the functions that you call in your source code is cryptographically secure, most of them are harmful enough that using one of them may be unsafe even in combination with other protected functions. MD5 has security issues (although they may not be relevant for this application). Uniqid not only does not generate cryptographically random bytes by default (since it uses the system clock), the added entropy that you pass is combined using a linear congruent generator that is not cryptographically secure. In fact, this probably means that you can guess all of your API keys provided to access some of them, even if they had no idea about the cost of your server clock. Finally, mt_rand (), which you use as extra entropy, is also not a protected random number generator.

+6
Sep 17 '13 at 4:56 on
source share

There is no simple function in php that changes a byte string directly to a character string, it must be implemented by ourselves! For example: PHP password generator .

-four
May 09 '17 at 23:47
source share



All Articles