Generating Unique Hashes in Magento 2 Programmatically

Occasionally, we often encounter scenarios where generating unique hash tokes is necessary. Hash tokens play a crucial role in various aspects of Magento 2 development, such as security, URL generation, form submission, and more. In this blog post, we will explore different methods to generate unique hash tokens in Magento 2, ensuring their uniqueness and cryptographic strength.

Using Magento’s Built-in Cryptographic Hashing Functions

Magento 2 provides a set of cryptographic hashing functions that can be leveraged to generate unique hashes. The following steps will describe how to use this method.

Inject the \Magento\Framework\Math\Random class into your custom class or block.

    /**
     * @param \Magento\Framework\Math\Random $random
     */
    public function __construct(
        private readonly \Magento\Framework\Math\Random $random
    ) {
    }

Use the getRandomString() method of the Random class to generate a random string. Specify the desired length of the hash token as an argument.

/**
 * This will generate a hash of 32 characters using:
 * - Lowercase alphabet characters (a-z)
 * - Uppercase alphabet characters (A-Z)
 * - Numbers (0-9)
 * Example: aD45f45FtT6FaaD678GfsfTfa9faFrf8
 */
$uniqueHash = $this->random->getRandomString(32);

You can optionally pass an additional $chars argument to limit the characters used in the random string generation, ensuring compatibility with specific requirements.

        /**
         * Because I'm passing the $chars as parameter, this will generate a hash of 17 characters using:
         * - Numbers (0-9)
         * Example: 89093716230023760
         */
        $uniqueHash = $this->random->getRandomString(17, '0123456789');

The generated random string will serve as your unit hash token.

Here’s a full example of how to use it.

<?php

namespace MagedIn\ExampleModule\Model;

class ExampleClass
{
    public function __construct(
        private readonly \Magento\Framework\Math\Random $random
    ) {
    }

    public function run()
    {
        /**
         * This will generate a hash of 32 characters using:
         * - Lowercase alphabet characters (a-z)
         * - Uppercase alphabet characters (A-Z)
         * - Numbers (0-9)
         * Example: aD45f45FtT6FaaD678GfsfTfa9faFrf8
         */
        $uniqueHash = $this->random->getRandomString(32);

        /**
         * Because I'm passing the $chars as parameter, this will generate a hash of 17 characters using:
         * - Numbers (0-9)
         * Example: 89093716230023760
         */
        $uniqueHash = $this->random->getRandomString(17, '0123456789');

        /**
         * Because I'm passing the $chars as parameter, this will generate a hash of 22 characters using:
         * - Lowercase alphabet characters (a-z)
         * Example: aofiuhiaurghaoiuhgaghs
         */
        $uniqueHash = $this->random->getRandomString(22, 'abcdefghijklmnopqrstuvxyz');
    }
}

Utilizing PHP’s Built-in Cryptographically Secure Functions

Magento 2 is built on PHP, which offers several built-in functions for generating cryptographically secure random strings. Here’s how you can leverage these functions to generate a unique hash token.

Use the random_bytes() function to generate a string of cryptographically secure random bytes.

$random = random_bytes(32);

Convert the random bytes into a hexadecimal representation using the bin2hex() function. Optionally, trim the hexadecimal string to the desired length to obtain your unique hash token.

$random = random_bytes(32);
$random = bin2hex($random);

Combining Unique Identifiers with Hashing Functions

Sometimes, you may need to generate hashes that include additional unique identifiers, such as customer IDs or order IDs. Here’s an approach to generate a unique hash token by combining identifiers and hashing functions.

Gather the unique identifier(s) you want to include in the hash token, such as a customer ID or order ID, and concatenate the identifiers along with any additional data you want to include.

$customerId = 123;
$orderId = 345;
$data = $customerId . $orderId;

Apply a hashing function, such as md5(), sha1(), or more secure options like hash('sha256', $data), to generate the hash value. Here’s an example of how to do that.

$customerId = 123;
$orderId = 345;
$data = $customerId . $orderId;
$encrypted = hash('sha256', $data);

Generating unique hash tokens in Magento 2 is a common requirement for various functionalities. Whether you need them for security purposes, generating unique URLs, or form submissions, employing proper techniques ensures they are unique and pretty secure. This blog post explored a few different methods to generate unique hashes in Magento 2, including leveraging Magento’s cryptographic functions, utilizing PHP’s built-in secure functions, and combining unique identifiers with hashing functions.

Remember to choose the appropriate method based on your specific requirements, such as the desired length and level of cryptographic strength. By generating unique hash tokens, you enhance the security and reliability of your Magento 2 applications, contributing to a seamless and robust user experience.

Stay tuned for more Magento 2 tips and best practices to level up your development skills!

Leave a comment