Encryption and Decryption in Configuration in Magento 2

If you are working with APIs or any secret keys, than you will need to encrypt those keys and store it in Configuration (core_config_data) instead of in a visible form.

Below are the steps to do that,

1) Encryption: In your Namespace/Module/etc/adminhtml/system.xml, you need to add a class inside backend_model tag that does the encryption, and add a property type=”obscure” to the field

<field id="access_key" translate="label comment" type="obscure" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1">
    <label>Access Key ID</label>                    
    <backend_model>Magento\Config\Model\Config\Backend\Encrypted</backend_model>
    <validate>required-entry</validate>
</field>

2) Decryption: In your helper class inject dependency class Magento\Framework\Encryption\EncryptorInterface

<?php

namespace Namespace\Module\Helper;

use Magento\Store\Model\ScopeInterface;

class Data
{
    protected $_encryptor;
    protected $_scopeConfig;

    public function __construct(
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
        \Magento\Framework\Encryption\EncryptorInterface $encryptor,
    ) {
        $this->_scopeConfig = $scopeConfig;
        $this->_encryptor = $encryptor;        
   }


   /**
     * @param null $storeId Store Id
     * @return string|null
     */
    public function getAccessKey($storeId = null)
    {
        $accessKey = $this->_scopeConfig->getValue(
            'access_key',
            ScopeInterface::SCOPE_STORE,
            $storeId
        );

        return (!empty($accessKey)) ? $this->_encryptor->decrypt($accessKey) : null;
    }//end getAccessKey()
}

Hope it is helpful.

Leave a Reply

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

Scroll to top