How to generate a criptographically secure random string with Symfony (and Php)

In some circumstances knowing how to generate a criptographically secure random string could avoid to introduce a security breach in your application. If you want to create a random password for a new user or a cryptographic key, you’d better use a strong algorithm which guarantees unpredictable values. But first things first….

Where is the problem?

As is well known computers can’t create true random values (except when equipped with peculiar hardware); algorithms generate pseudo random values trying to emulate real random sequences.

For our purpose, we can group algorithms into two types:

  • strong algorithms: random values are guaranteed to be unique, unpredictable, not reproducible;

  • weak algorithms, none of the above.

Strong algorithms are good for criptographically secure random values, weak ones are not.

When should we use criptographically secure random values? Everytime we are developing functionalities which impact on security. For example:

  • temporary passwords;

  • criptographic keys;

  • temporary API’s access tokens.

Using weak algorithms in these situations could introduce exploitable vulnerabilities in your application (see more here).

The solution: random_bytes

Using the function random_bytes comes in help.

In Symfony, it is available as:

  • native function for Php >= 7.0;

  • a polyfill for previous versions.

This function always guarantees to use a strong algorithm (an exception will be thrown if none is available); Symfony documentation advices us to use it in conjunction with an hash function (sha1, md5), to avoid errors when writing to database or generating urls due to the (possible) presence of the char “\0”.

What about openssl_random_pseudo_bytes?

One possible alternative to random_bytes is openssl_random_pseudo_bytes. This function now uses, if one is available, a strong algorithm: it was indeed fixed in 2016.

However, when compared with random_bytes, it requires some additional configurations:

  • it can be used only after enabling OpenSSL extension;

  • the effective usage of a strong algorithm must be verified testing the second, by reference parameter ($crypto_strong – if false the function uses a weak one).

Common pitfall

A possible mistake, in the scenario depicted above, consists in using php functions based on weak algorithms. When we need criptographically secure values these php functions must be avoided:

  • rand

  • mt_rand

  • uniquid

  • lcg_value

We’re always looking for talented developers… find out all open job positions!

Nicola Fornaciari
Nicola Fornaciari
Articoli: 3

Lascia una risposta

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *

Questo sito usa Akismet per ridurre lo spam. Scopri come i tuoi dati vengono elaborati.