Hashing
Introduction
Passwords should never be stored, only their hashes. A hash is a one-way fingerprint: you can check whether a password produces it, but you cannot work backwards from the hash to the password. The Hasher in @plinthjs/encryption hashes passwords with scrypt, a memory-hard algorithm built into Node. It needs no native add-on to install.
pnpm add @plinthjs/encryptionEach hash includes a random salt and records the parameters it was made with, so you can raise the cost later and still verify old hashes.
Hashing and checking passwords
make() hashes a password and check() verifies one against a stored hash:
import { Hasher } from '@plinthjs/encryption'
const hasher = new Hasher()
const hash = hasher.make('correct horse battery staple')
// => 'scrypt$16384$8$1$<salt>$<digest>'
hasher.check('correct horse battery staple', hash) // => true
hasher.check('wrong password', hash) // => falseHashing the same password twice gives two different strings because each uses a new salt. Always compare with check(), never by comparing hashes yourself. check() runs in constant time and returns false (instead of throwing) when the stored value is not a valid hash:
hasher.check('anything', 'not a hash') // => falseTIP
scrypt is deliberately slow. Hashing takes tens of milliseconds, and the work is synchronous, so a login endpoint blocks the event loop for that long. This is the intended trade-off: it makes guessing attacks expensive. Rate limit your login routes (see Rate Limiting).
The hash format
A hash is a $-separated string: the algorithm name, the cost N, the block size r, the parallelism p, the base64 salt, and the base64 digest. Everything needed to verify the password except the password itself is in the string. info() parses a hash for you and isHashed() tells you whether a value is already a hash:
hasher.info(hash)
// => { algorithm: 'scrypt', options: { cost: 16384, blockSize: 8, parallelism: 1 } }
hasher.isHashed(hash) // => true
hasher.isHashed('plain text') // => false
hasher.info('plain text') // => nullisHashed() is useful when a model setter should hash a password only if it has not been hashed yet.
Tuning the cost
The Hasher constructor takes the default scrypt parameters, all optional:
| Option | Default | Meaning |
|---|---|---|
cost | 16384 | CPU and memory cost (N). Must be a power of two. |
blockSize | 8 | Block size (r). |
parallelism | 1 | Parallelization (p). |
const strong = new Hasher({ cost: 32768 })
strong.make('secret')You can also override the parameters for a single call with make('secret', { cost: 2048 }). Higher cost is slower for you and for an attacker. Choose the highest value your servers can afford at login time.
In tests, use a small cost to keep the suite fast, for example new Hasher({ cost: 1024 }). Never ship that to production.
Upgrading hashes over time
As hardware gets faster you will want to raise the cost. needsRehash() tells you whether a stored hash was made with different parameters than the hasher's current ones (or than the options you pass). It also returns true for a value that is not a valid hash:
const old = new Hasher({ cost: 1024 }).make('secret')
hasher.needsRehash(old) // => true (made with a lower cost than the defaults)
hasher.needsRehash(hash) // => false
hasher.needsRehash(hash, { cost: 32768 }) // => trueThe moment of upgrade is a successful login, when you have the plaintext password in hand. You do not need to write that code in an application that uses the session guard from Authentication: when a login succeeds, the guard asks the provider to rehash if required, and ArrayUserProvider replaces a stale hash automatically. When you write your own provider, do it yourself:
async rehashPasswordIfRequired(user: Authenticatable, credentials: Credentials): Promise<void> {
const password = String(credentials['password'])
if (this.hasher.needsRehash(user.getAuthPassword())) {
await this.store(user, this.hasher.make(password))
}
}Checking your configuration
verifyConfiguration() confirms that the cost parameters are valid (the cost is a power of two greater than one, the block size and parallelism are positive integers) and that a test hash round-trips with them. It returns a boolean, which makes it a handy startup check when the cost comes from an environment variable:
hasher.verifyConfiguration() // => true
hasher.verifyConfiguration({ cost: 1000 }) // => false (not a power of two)
new Hasher({ cost: 1000 }).verifyConfiguration() // => falseConstructing a Hasher with a bad cost does not throw. The error surfaces on the first make(), so run verifyConfiguration() at boot to fail early.
Using hashes elsewhere
The same Hasher is what the rest of the framework expects. Pass it to ArrayUserProvider and ArrayTokenRepository from @plinthjs/auth and to the Accounts options in @plinthjs/accounts:
import { ArrayUserProvider, GenericUser } from '@plinthjs/auth'
const provider = new ArrayUserProvider(
[new GenericUser({ id: 1, email: 'ada@example.com', password: hasher.make('secret') })],
hasher,
)Hashing is for values you only need to verify. Use Encryption for values you need to read back, and see API Tokens for why high-entropy random tokens use a fast SHA-256 digest instead of scrypt.
Related
- Authentication for logging users in with hashed passwords.
- Accounts for registration and password-change actions.