You are viewing the legacy version of AdonisJS. Visit https://adonisjs.com for newer docs. This version will receive security patches until the end of 2021.

Encryption and Hashing

Table of Contents

AdonisJs ships with providers for hashing values and encrypting data.

Hashing values is different to encrypting data, since hashed values cannot be decrypted once encrypted.

Encrypting Data

The AdonisJs encryption provider uses the Node.js crypto module to encrypt and decrypt values.

Your appKey must be defined inside the config/app.js file before you can encrypt values.

encrypt(value)

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

decrypt

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

Hashing Values

The AdonisJs hash provider comes with multiple drivers to hash user data.

By default it uses bcrypt, however there is Argon support via the argon2 npm package.

Multiple drivers are supported by @adonisjs/framework version >=5.0.8.

Config

The config is defined inside the config/hash.js file:

config/hash.js
module.exports = {
  driver: 'bcrypt',
  bcrypt: {
    rounds: 10
  },
  argon: {
    type: 1
  }
}
If using the argon driver, you will have to install the argon2 npm package package via npm.

make(value, [config])

Hash a plain string value:

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

Optionally, inline config can be passed to override config file defaults:

const Hash = use('Hash')
const safeExample = await Hash.make('example', config)

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 = await Hash.verify('plain-value', 'hashed-value')

if (isSame) {
  // ...
}