How to generate unique hash token in Magento 2?

In Magento 2, You can generate a unique hash token for your custom functionality where you need to pass id or variable as encrypted.

Magento uses this functionality, generate a unique hash token for reset password confirmation link.

If you want to do a generate unique token you need to use Core Magento\Framework\Math\Random class to accomplish your requirement.

I have created a Block to add function and dependency class,

<?php
class Demo extends \Magento\Framework\View\Element\Template
{
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Framework\Math\Random $mathRandom,
        array $data = []
    ) {
        $this->mathRandom = $mathRandom;
        parent::__construct($context,$data);
    }

    // Generate unique token
    public function generateUniqueToken()
    {
        return $this->mathRandom->getUniqueHash();
    }
}

You can use this function with $this->generateUniqueToken() to anywhere in your class or use in template with $block->generateUniqueToken();

The result will be unique string look like, MmoZyEKE3RtZKxcSS1rau0rkie2ZvttQ