Support AdonisJs development by becoming a patron
Support AdonisJs

Encryption & Hashing

Data ships with a couple of providers for hashing values and encrypting data. Hashing values are different from encryption since hashed values cannot be decrypted once encrypted that is not the case with encryption.


To make use of Encryption or Hashing, you must set up their providers inside the bootstrap/app.js file.

const providers = [
  // ...
  // ...

Also, it is recommended to setup aliases for both inside the same file.

const aliases = {
  // ...
  Encryption : 'Adonis/Src/Encryption',
  Hash: 'Adonis/Src/Hash'
  // ...

Encrypting Data

AdonisJs encryption provider makes use of Node.js crypto module to encrypt and decrypt values. By default all values are encrypted with a SALT using aes-256-cbc algorithm.

Make sure that appKey inside config/app.js is defined before you can encrypt values.


const Encryption = use('Encryption')
const encrypted = Encryption.encrypt('hello world')


const Encryption = use('Encryption')
const decrypted = Encryption.decrypt('encrypted value')

Hashing Values

AdonisJs hash provider makes use of bcrypt to hash values which is a slow algorithm to hash/verify a value.

Bcrypt is commonly used to hash passwords, and since it is a slow algorithm, it makes it expensive(if not impossible) for attackers to crack a password. The slowness of the algorithm is based upon the number of rounds to be executed before returning the hashed value.

By default, the hash provider will make use of 10 rounds which will take approximately 1500ms to hash the value.

make(value, [rounds=10])

const Hash = use('Hash')
const safePassword = yield Hash.make(request.input('password'))

// or
const safePassword = yield Hash.make(request.input('password'), 20)

verify(value, hashedValue)

Since you cannot decrypt a hash, you can verify the user input against the previously hashed value.

const Hash = use('Hash')
const isSame = yield Hash.verify('plain-value', 'hashed-value')

if (isSame) {
  // ...