Skip to content

Hashing ​

Hash hashes passwords and other secrets one way, and checks a value against a hash. It has three drivers:

DriverPackageNotes
scrypt (default)none, built into Node.jsN = 2^17, r = 8, p = 1 (OWASP)
bcryptbcrypt (native) or bcryptjs12 rounds. Values over 72 bytes are refused
argon2argon2argon2id, 19 MiB, 2 iterations, 1 lane (OWASP)

scrypt needs no install, so it's the default. For the others, install the package; without it, Hash throws [Megh] argon2 is not installed. Run: npm install argon2.

sh
npm i argon2       # argon2
npm i bcrypt       # bcrypt, native
npm i bcryptjs     # bcrypt, pure JavaScript

With both bcrypt and bcryptjs installed, Megh uses bcrypt.

Hashing and checking ​

Inject Hash like any service:

ts
import { AppService, Hash } from '@meghjs/core';

@AppService
export class AccountService {
  constructor(private readonly hash: Hash) {}

  async register(email: string, password: string) {
    return User.create({ email, password: await this.hash.make(password) });
  }

  async signIn(email: string, password: string) {
    const user = await User.findBy('email', email);
    if (!user || !(await this.hash.check(password, user.password))) {
      throw new UnauthorizedException('Invalid email or password.');
    }
    return user;
  }
}

Outside a class, call the same methods on Hash itself, or on the hash helper:

ts
import { Hash, hash } from '@meghjs/core';

const hashed = await Hash.make('secret');
await hash.check('secret', hashed); // true
  • make(value, options?) hashes value with the default driver and a new random salt, so the same value gives a different hash each time.
  • check(value, hashed) returns true when they match. It reads the algorithm from the hash, so it checks scrypt, bcrypt and argon2 hashes whatever the default driver is. A wrong value, an empty or malformed hash, or one Megh doesn't know returns false. It only throws when the hash needs a package that isn't installed.
  • needsRehash(hashed, options?) returns true when hashed was made by another driver or with other settings than the current ones.
  • driver(name) gives one driver with its configured settings: hash.driver('bcrypt').make(value).

Comparisons run in constant time. Megh never logs the values it hashes.

Settings ​

Pick the driver and its settings with app.useHashing():

ts
app.useHashing({
  driver: 'argon2',
  argon2: { memoryCost: 19456, timeCost: 2, parallelism: 1 },
});

Or with an @AppConfig class, the same way as other use* settings:

ts
import { AppConfig, MeghConfig, type HashingConfig } from '@meghjs/core';

@AppConfig
export class HashingSettings extends MeghConfig<HashingConfig> {
  config(): HashingConfig {
    return { driver: 'bcrypt', bcrypt: { rounds: 12 } };
  }
}
ts
app.useHashing(HashingSettings);
SettingDefault
driverscryptscrypt, bcrypt or argon2
scrypt.cost131072N, a power of two
scrypt.blockSize8r
scrypt.parallelization1p
scrypt.saltLength16Bytes, at least 16
scrypt.keyLength64Bytes
bcrypt.rounds124 to 31; each step doubles the time
argon2.memoryCost19456KiB
argon2.timeCost2Iterations
argon2.parallelism1Lanes

An unknown driver or an invalid setting throws when useHashing() runs. Without useHashing(), Hash uses scrypt with the defaults.

scrypt hashes look like scrypt$<N>$<r>$<p>$<salt>$<hash> (base64). bcrypt and argon2 hashes use their usual formats ($2b$12$..., $argon2id$v=19$...).

bcrypt and long passwords ​

bcrypt only reads the first 72 bytes of a value. Instead of hashing a cut-off value, make() throws a HashingError for anything longer (and for values containing a NUL character). Bytes, not characters: é is two bytes. Limit password length in your DTO, or use argon2 or scrypt.

Upgrading old hashes ​

When you change the driver or raise the cost, existing hashes keep working, because check() reads the algorithm from each hash. Rehash a user's password the next time they sign in:

ts
if (await this.hash.check(password, user.password)) {
  if (this.hash.needsRehash(user.password)) {
    user.password = await this.hash.make(password);
    await user.save();
  }
}

megh scaffold:auth writes this into AuthService.login(). Hashes from earlier versions of scaffold:auth (scrypt$<salt hex>$<hash hex>) still check, and needsRehash() returns true for them.

Tests ​

Hashing is slow on purpose. In tests, make it cheap:

ts
import { Hash } from '@meghjs/core';

beforeAll(() =>
  Hash.configure({
    scrypt: { cost: 1024 },
    bcrypt: { rounds: 4 },
    argon2: { memoryCost: 1024, timeCost: 1 },
  }),
);
afterAll(() => Hash.reset());

Hash.configure() takes the same options as useHashing(), and Hash.reset() goes back to scrypt with the defaults. Don't use these settings outside tests.

From the command line ​

megh make:hash prints a hash, for example for a seeder, or checks a value against one:

sh
megh make:hash < password.txt
megh make:hash --bcrypt --rounds 10 < password.txt
megh make:hash --verify '$2b$12$...' < password.txt   # prints match or no match

See CLI: Hashing a value.

Released under the MIT License.