← Runnable Projects

阅读中文版本

Bcrypt Hash and Verify CLI

A small Node CLI that hashes a password with bcrypt at a configurable cost and verifies a password against a stored hash.

beginnerjavascriptunverified

Project

node-bcrypt-hash-cli

Entry point: bcrypt-cli.mjs

Install

pnpm add bcryptjs

Run

node bcrypt-cli.mjs hash "correct horse" 10

Test

node --test bcrypt.test.mjs

Expected output

Prints a salted bcrypt hash starting with $2, and verify prints true when the password matches the hash and false otherwise.

Dependencies

  • bcryptjs ^2.4.3
  • node >=20

What it does

Derives a slow, salted hash so that offline guessing is expensive, and exposes the cost factor in the output. Verification re-derives the hash using the salt read from the stored value.

import bcrypt from 'bcryptjs';

const [mode, password, arg] = process.argv.slice(2);
if (!mode || !password) { console.error('usage: bcrypt-cli <hash|verify> <password> [cost|hash]'); process.exit(1); }

if (mode === 'hash') {
  const cost = arg ? Number(arg) : 10;
  console.log(await bcrypt.hash(password, cost));
} else {
  console.log(await bcrypt.compare(password, arg));
}

Run and verify

node bcrypt-cli.mjs hash "correct horse" 10

Run the test command to check the implementation: node --test bcrypt.test.mjs.

Expected Output

The hash embeds the algorithm, cost, and salt, so it looks like $2a$10$ followed by 53 characters. Verifying the same password prints:

true

Limitations

Choose the cost so hashing takes roughly a tenth of a second on your hardware; a cost tuned on a fast laptop can be too weak on a server or too slow on a constrained device.