How to encrypt and decrypt string in Magento 2?

You can Encrypt or Decrypt any string using Magento 2 with native interface functionality.

You can encrypt or decrypt password or credit card data or any value you need to encrypt using Magento\Framework\Encryption\EncryptorInterface interface.

Example, You can encrypt the password with below way,

<?php
use Magento\Framework\Encryption\EncryptorInterface;

public function __construct(
    EncryptorInterface $encryptor
) {
    $this->encryptor = $encryptor;
}

/**
 * Encrypt password
 *
 * @param   string $password
 * @return  string
 */
public function encryptPassword($password)
{
    return $this->encryptor->encrypt($password);
}

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

You need to call for encrypt,

$this->encryptPassword(“PASSWORD”)

and Decrypt,

$this->decryptPassword(“PASSWORD”)