Back to Top

How to Encrypt and Decrypt URL Parameter in Magento 2

Updated 22 July 2024

Hello Friends!!

In this blog, we will learn how we can pass an encrypted request parameter in the GET method’s requests and decrypt the request parameter to use the value further.

What is Encryption?

Encryption is the process of translating plain text data (plaintext) into something that appears to be random and meaningless (ciphertext) that no one can understand. 

What is Decryption?
Decryption is the process of converting ciphertext back to plaintext.

Why do we need encryption/decryption?
For Example, if we want to pass an id for any particular record row like product ID or user id, or entity id using URL, then we pass the URL as shown below:

http://127.0.0.1/magento/routename/controller/actionname/id/1/

In this case, if any unauthorized person found the URL, and passes the parameter, he/she can delete/view/edit or perform any action (which is mentioned in the controller code) for all the records and destroy our business.

Searching for an experienced
Magento 2 Company ?
Find out More

So, to prevent your store from inauthentic access, use the below solution.

Step1. We will create a Helper.php file inside the app/code/Vendor/Module/Helper directory.

<?php
namespace Vendor\Module\Helper;

use Magento\Framework\Url\DecoderInterface;
use Magento\Framework\Url\EncoderInterface;

/**
 * helper class.
 */
class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
    /**
     *
     * @param EncoderInterface $urlEncoder
     * @param DecoderInterface $urlDecoder
     * @param \Magento\Framework\App\Helper\Context $context
     * @param \Magento\Framework\Encryption\EncryptorInterface $encryptor
     */
    public function __construct(
        EncoderInterface $urlEncoder,
        DecoderInterface $urlDecoder,
        \Magento\Framework\App\Helper\Context $context,
        \Magento\Framework\Encryption\EncryptorInterface $encryptor
    ) {
        $this->urlEncoder = $urlEncoder;
        $this->urlDecoder = $urlDecoder;
        $this->encryptor = $encryptor;
        
        parent::__construct($context);
    }
    
    /**
     * @param $url
     * @return string
     */
    public function encodeUrl($url)
    {
        return $this->urlEncoder->encode($url);
    }
 
    /**
     * @param $url
     * @return string
     */
    public function decodeUrl($url)
    {
        return $this->urlDecoder->decode($url);
    }
    
    /**
     * Encrypt string
     *
     * @param   string $str
     * @return  string
     */
    public function encryptString($str)
    {
        return $this->encryptor->encrypt($str);
    }

    /**
     * Decrypt string
     *
     * @param   string $str
     * @return  string
     */
    public function decryptString($str)
    {
        return $this->encryptor->decrypt($str);
    }
}

Step2. Encrypt the parameter: You can encrypt the request parameter in your required file. Here I have created a controller Index.php inside the app/code/Vendor/Module/Controller/Index directory.

In which, I have encrypted the value of the id request parameter and passed the id parameter in another controller GetParams.php file which is created inside the app/code/Vendor/Module/Controller/Index directory.

<?php
namespace Vendor\Module\Controller\Index;

use Magento\Framework\App\Action\HttpGetActionInterface as HttpGetActionInterface;
use Magento\Framework\View\Result\PageFactory;
use Magento\Framework\App\Action\Context;

class Index extends \Magento\Framework\App\Action\Action implements HttpGetActionInterface
{
    /**
     * @var \Magento\Framework\Controller\Result\RedirectFactory
     */
    protected $resultRedirectFactory;

    /**
     * @param Context $context
     * @param \Vendor\Module\Helper\Data $demoHelper
     * @param \Magento\Store\Model\StoreManagerInterface $storeManager
     * @param \Magento\Framework\Controller\Result\RedirectFactory $resultRedirectFactory
     */
    public function __construct(
        Context $context,
        \Vendor\Module\Helper\Data $demoHelper,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Framework\Controller\Result\RedirectFactory $resultRedirectFactory
    ) {
        $this->demoHelper   = $demoHelper;
        $this->_storeManager = $storeManager;
        $this->resultRedirectFactory = $resultRedirectFactory;
        parent::__construct($context);
    }

    /**
     * Index Controller Execute Method
     *
     * @return \Magento\Framework\Controller\Result\Redirect|\Magento\Framework\View\Result\Page
     */
    public function execute()
    {
        $userId = "10";
        $id = $this->demoHelper->encryptString($userId);

        $encryptedId = $this->demoHelper->encodeUrl($id);

        $redirectionUrl = "";
        $baseUrl = $this->_storeManager->getStore()
            ->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_WEB);
        $redirectionUrl = $baseUrl."demo/index/getParams/id/".$encryptedId;
        
        /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
        $resultRedirect = $this->resultRedirectFactory->create();
        $resultRedirect->setUrl($redirectionUrl);
        return $resultRedirect;
    }
}

Step3. Decrypt the parameter: You can decrypt the parameter value in your required file as in the following code. Here I have decrypted the id parameter’s value in GetParams.php controller as following:

<?php
namespace Vendor\Module\Controller\Index;

use Magento\Framework\App\Action\HttpGetActionInterface as HttpGetActionInterface;
use Magento\Framework\App\ResponseInterface;
use Magento\Framework\Controller\ResultInterface;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\Action\Action;

class GetParams extends Action implements HttpGetActionInterface
{
    /**
     * @param Context $context
     * @param \Vendor\Module\Helper\Data $helper
     * @param \Magento\Store\Model\StoreManagerInterface $storeManager
     * @param \Magento\Framework\Controller\ResultFactory $resultFactory
     */
    public function __construct(
        Context $context,
        \Vendor\Module\Helper\Data $helper,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Framework\Controller\ResultFactory $resultFactory
    ) {
        $this->helper        = $helper;
        $this->resultFactory = $resultFactory;
        $this->_storeManager = $storeManager;
        
        parent::__construct($context);
    }

    /**
     * Execute Method to display the parameter value
     *
     * @return ResponseInterface|ResultInterface
     */
    public function execute()
    {
        $userIdHash = $this->getRequest()->getParam("id", "");
        $userId = 0;
        if (!empty($userIdHash)) {
            $decryptedHash = $this->helper->decodeUrl($userIdHash);
            $decryptedHash = str_replace(" ", "+", $decryptedHash);
            $userId = (int)$this->helper->decryptString($decryptedHash);
            echo "USER ID:$userId";
            die();
        }
        $resultRedirect = $this->resultFactory->create(
            \Magento\Framework\Controller\ResultFactory::TYPE_REDIRECT
        );
        $redirectionUrl = $this->_storeManager->getStore()
            ->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_WEB);
        $result = $resultRedirect->setUrl($redirectionUrl);
        return $result;
    }
}

Step4. Now, when you will hit the http://<your-ip>/<magentoroot-path>/demo/index/index URL in the browser it will be redirected to the getParams controller and the result will be as in the following images:

indexUrl
Run index controller in browser
getParamsUrl
Result of Encrypted id parameter value after Decryption

Hope this will be helpful.
Thanks 🙂

. . .

Leave a Comment

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


Be the first to comment.

Back to Top

Message Sent!

If you have more details or questions, you can reply to the received confirmation email.

Back to Home