Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating cryptographically secure tokens

In order to generate a 32 character token for access to our API we currently use:

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

I have read that this method is not cryptographically secure as it's based on the system clock, and that openssl_random_pseudo_bytes would be a better solution as it would be harder to predict.

If this is the case, what would the equivalent code look like?

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

$token = md5(openssl_random_pseudo_bytes(32)); 

Also what length makes sense that I should pass to the function?

like image 739
fire Avatar asked Sep 16 '13 14:09

fire


People also ask

What is cryptographically secure token?

2. A token where the secret is a cryptographic key. Source(s): 1. A portable, user-controlled, physical device (e.g., smart card or PC card) used to store cryptographic information and possibly also perform cryptographic functions.

How do you generate a token in Python?

You can call it from the save() method of your model. It generates a candidate token using a defined function, searches the existing rows in the database for that candidate token. If it finds one, it trys again, otherwise, it returns the candidate string.


1 Answers

Here is the correct solution:

$token = bin2hex(openssl_random_pseudo_bytes(16));  # or in php7 $token = bin2hex(random_bytes(16)); 
like image 121
fire Avatar answered Oct 19 '22 09:10

fire