Search code examples
phpcryptographytokenphp-openssl

How to use openssl_random_pseudo_bytes function ? php


I want to generate token , to use it as sign in auth, so I want to assure that the token algorithm is cryptographically strong !

I am using this block of code to to achieve that :

$crypto_strong = false;
while($crypto_strong !== false)
$openssl =openssl_random_pseudo_bytes(128,$crypto_strong);
$token = bin2hex($openssl);

is that correct ?


Solution

  • Reading the docs, it describes the $crypto_strong parameter as:

    If passed into the function, this will hold a boolean value that determines if the algorithm used was "cryptographically strong", e.g., safe for usage with GPG, passwords, etc. TRUE if it did, otherwise FALSE

    The value of $crypto_strong is going to be fixed for a particular system. So if your system doesn't use a strong algorithm, your code will enter an infinite loop.

    According to those same docs, "it's rare for this to be FALSE, but some systems may be broken or old". So it sounds like you are unlikely to encounter may examples of a false value. Perhaps in those situations, it would be more appropriate to abort the procedure and present an error to the user.

    I wasn't entirely clear on your background use case, so I've no idea whether this general approach is correct for you. But certainly your posted code is wrong.