How to encrypt password in Magento 2?

Firstly my usual comment would be, do not encrypt a password!

  • Encryption = A two-way process, scrambling and then unscrambling data at a later date.
  • Hashing = A one-way process, create an encrypted looking string from a given input.

Hashing is not encryption, once you have something hashed it cannot be unhashed. Think of it like this you can md5 hash the entire contents of "Harry Potter and the Philosopher's Stone" and end up with a 32 character string, there is no way to get from that 32 characters back to the full book.

Hashing is usually preferable when storing passwords as it means you don't actually ever store the password but merely the result of its hash meaning if you're ever compromised your users can feel a little safer about the whole ordeal.

Anyway, to encrypt data

use \Magento\Framework\Encryption\EncryptorInterface
$encrypt = $this->encryptor->encrypt($data);
$decrypt = $this->encryptor->decrypt($data);

To hash a password

use \Magento\Framework\Encryption\EncryptorInterface
$hash = $this->encryptor->hash($password);

#Hash is persisted in the database when you next login use 
#provided password variable and compare with stored hash

$bool = $this->encryptor->validateHash($password, $hash);

For more thorough example usage of password, hashing have a look a

  • Magento\Customer\Model\Customer::setPassword
  • Magento\Customer\Model\Customer::validatePassword

I searched a little and found out that magento2 uses EncryptorInterface class to encrypt and decrypt the password.

You can use it this way:

use Magento\Framework\Encryption\EncryptorInterface as Encryptor;

in the construct function :

$this->encryptor = $encryptor;

then call encrypt function to encrypt:

$encrypt = $this->encryptor->encrypt($password);

and to decrypt:

$decrypt = $this->encryptor->decrypt($password);