PHP: Generate cryptographically secure token

Intro

Sometimes we need to create a random string or token using PHP. For example, it’s quite common that when we want to reset our password on some website a message is sent to the mail we registered.

Probably the message have a link like this:

site.com/reset-pass?token=123

Where 123 is the token. Today we will see how to create a token cryptographically secure using PHP. We can use this token as a password or as random string to reset something.

This works for PHP 5 and for PHP 7.

Generate cryptographically secure token using PHP

Let’s see how to generate a token in PHP, which is nothing more than a set of characters that should not be guessed in any way (except by brute force, but that’s another story).

There are 2 versions of this script, the first for PHP 5 and the second for PHP 7.

This is because PHP 7 incorporates new functions that are not present in the other versions, so we must look for alternatives.

In PHP 5

If we use PHP in its version 5 (although we should update) this will generate a secure token:

#<?php
function generar_token_seguro($longitud)
{
    if ($longitud < 4) {
        $longitud = 4;
    }
 
    return bin2hex(openssl_random_pseudo_bytes(($longitud - ($longitud % 2)) / 2));
}

We divide the length between 2, since when representing each byte in hexadecimal format these are converted into 2 digits.

For example, “Hola” in hexadecimal is 48656c6c6f.

And to call it we call it with an argument: the length. That is, how many characters we want or the expected length of the string.

Examples:

generar_token_seguro(4) => 6149
generar_token_seguro(20) => e7e1f6ba640e3069cf84
generar_token_seguro(16) => b46ce8aac0e4460d
generar_token_seguro(7) => b7dbbf

It is important to note that when we pass 7 it actually returns a string of length 6, so we better pass even numbers and greater than 4.

PHP 7

We would modify the function and call random_bytes instead of openssl_random_pseudo_bytes. It looks like this:

#<?php
function generar_token_seguro($longitud)
{
    if ($longitud < 4) {
        $longitud = 4;
    }
 
    return bin2hex(random_bytes(($longitud - ($longitud % 2)) / 2));
}

Examples

We can call the function and it will return a random string like this:

generar_token_seguro(4) => 49ac
generar_token_seguro(20) => e613db7e8b4f50aaee0f
generar_token_seguro(16) => fd0e597e0639a401
generar_token_seguro(7) => 398896

Just as seen in the following image:

Demostración de cómo generar un token en PHP que sea seguro criptográficamente
Demostración de cómo generar un token en PHP que sea seguro criptográficamente

I am available for hiring if you need help! I can help you with your project or homework feel free to contact me.
If you liked the post, show your appreciation by sharing it, or making a donation

Leave a Comment

Your email address will not be published. Required fields are marked *