Categorías: AlgorithmsPHPSecurity

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

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

parzibyte

Freelancer programmer ready to work with you. Web, mobile and desktop applications. PHP, Java, Go, Python, JavaScript, Kotlin and more :) https://parzibyte.me/

Entradas recientes

Receipt designer for thermal printers – Free and open source

In the last months I have been working on a ticket designer to print on…

12 months hace

JavaScript: store and read files with the Origin Private File System

In this post you will learn how to use the Origin Private File System with…

1 year hace

JavaScript: download file with fetch

In this post you will learn how to download a file in the background using…

1 year hace

SQLite3 with vanilla JavaScript and OPFS – Hello world

In this post I will show you how to use SQLite3 directly in the web…

1 year hace

Python Thermal Printing: A Comprehensive Guide for Printing on Thermal Printers

In this tutorial, we'll explore how to effortlessly print receipts, invoices, and tickets on a…

1 year hace

Image printing on Thermal printer

When printing receipts on thermal printers (ESC POS) sometimes it is needed to print images…

1 year hace

Esta web usa cookies.