### Installation Error Example Source: https://github.com/kelektiv/node.bcrypt.js/blob/master/README.md This error message indicates that you are using a pre-release version of Node.js, which is not supported by node-gyp. Ensure you are using a stable version of Node.js for installation. ```bash gyp ERR! stack Error: "pre" versions of node cannot be installed, use the --nodedir flag instead ``` -------------------------------- ### Install Build Tools on OpenSUSE Source: https://github.com/kelektiv/node.bcrypt.js/wiki/Installation-Instructions Installs the necessary C++ compiler and make utility for compiling Node.js modules on OpenSUSE. ```bash sudo zypper install gcc-c++ make ``` -------------------------------- ### Install Dependencies and Run Tests Source: https://github.com/kelektiv/node.bcrypt.js/blob/master/README.md Standard npm commands to install project dependencies and execute the test suite. ```bash npm install ``` ```bash npm test ``` -------------------------------- ### Install bcrypt via NPM Source: https://github.com/kelektiv/node.bcrypt.js/blob/master/README.md Install the bcrypt library using npm. For OS X users encountering build errors, a specific command might be required before installation. ```bash npm install bcrypt ``` ```bash sudo xcode-select -switch /Applications/Xcode.app/Contents/Developer ``` -------------------------------- ### Install Windows Build Tools Source: https://github.com/kelektiv/node.bcrypt.js/wiki/Installation-Instructions Installs the necessary build tools for compiling Node.js modules on Windows using npm. ```bash npm install --global --production windows-build-tools ``` -------------------------------- ### Install Build Tools on Fedora Source: https://github.com/kelektiv/node.bcrypt.js/wiki/Installation-Instructions Installs the C++ compiler, make, and Python required for compiling Node.js modules on Fedora. ```bash dnf install gcc-c++ make ``` -------------------------------- ### Install Build Tools on Ubuntu/Debian Source: https://github.com/kelektiv/node.bcrypt.js/wiki/Installation-Instructions Installs essential build tools including a C++ compiler, make, and Python for compiling Node.js modules on Ubuntu and its derivatives. ```bash sudo apt-get install -y build-essential python ``` -------------------------------- ### Install bcrypt with custom binary host mirror Source: https://github.com/kelektiv/node.bcrypt.js/wiki/Frequently-Asked-Questions Use this command when your environment cannot reach GitHub to download pre-built binaries. Replace INTERNAL_HOST with your internal artifact repository URL. ```shell npm install bcrypt --bcrypt_lib_binary_host_mirror=https://INTERNAL_HOST/artifactory/node-pre-gyp-binaries ``` -------------------------------- ### Install Build Tools on RHEL/CentOS Source: https://github.com/kelektiv/node.bcrypt.js/wiki/Installation-Instructions Installs the C++ compiler, make, and Python necessary for compiling Node.js modules on RHEL and CentOS systems. ```bash yum install -y gcc-c++ make ``` -------------------------------- ### Install build dependencies on Alpine Linux Source: https://github.com/kelektiv/node.bcrypt.js/wiki/Installation-Instructions Installs necessary build tools for compiling native addons on Alpine Linux. Use --no-cache and --virtual for optimized container size. ```bash apk --no-cache add --virtual builds-deps build-base python ``` -------------------------------- ### Checking User Credentials (Async/Await) Source: https://github.com/kelektiv/node.bcrypt.js/blob/master/README.md An example of using `async/await` with `bcrypt.compare` to check user credentials after fetching user data. ```APIDOC ## Checking User Credentials (Async/Await) ```javascript async function checkUser(username, password) { //... fetch user from a db etc. const match = await bcrypt.compare(password, user.passwordHash); if(match) { //login } //... } ``` ``` -------------------------------- ### Hashing Passwords (Sync) Source: https://github.com/kelektiv/node.bcrypt.js/blob/master/README.md Provides examples for hashing passwords synchronously using bcrypt.js, with options to generate salt separately or auto-generate it. ```APIDOC ## Hashing Passwords (Sync) ### Technique 1: Generate salt and hash separately ```javascript const salt = bcrypt.genSaltSync(saltRounds); const hash = bcrypt.hashSync(myPlaintextPassword, salt); // Store hash in your password DB. ``` ### Technique 2: Auto-generate salt and hash ```javascript const hash = bcrypt.hashSync(myPlaintextPassword, saltRounds); // Store hash in your password DB. ``` ``` -------------------------------- ### ESM Import for bcrypt Source: https://github.com/kelektiv/node.bcrypt.js/blob/master/README.md Example of importing the bcrypt library using ECMAScript Modules (ESM) syntax. ```javascript import bcrypt from "bcrypt"; // later await bcrypt.compare(password, hash); ``` -------------------------------- ### Understanding BCrypt Hash Format Source: https://github.com/kelektiv/node.bcrypt.js/blob/master/README.md BCrypt hashes are 60 characters long and follow the format $[algorithm]$[cost]$[salt][hash]. This example breaks down each component. ```plaintext $2b$10$nOUIs5kJ7naTuTFkBy1veuK0kSxUFXfuaOKdOKf9xYT0KKIGSJwFa | | | | | | | hash-value = K0kSxUFXfuaOKdOKf9xYT0KKIGSJwFa | | | | | salt = nOUIs5kJ7naTuTFkBy1veu | | | cost-factor => 10 = 2^10 rounds | hash-algorithm identifier => 2b = BCrypt ``` -------------------------------- ### Handle Invalid Rounds Input for genSalt Source: https://context7.com/kelektiv/node.bcrypt.js/llms.txt This example demonstrates error handling for `bcrypt.genSalt` when an invalid type is provided for the 'rounds' parameter. The function expects a number. ```javascript // --- Error: rounds must be a number --- bcrypt.genSalt('10').catch(err => console.error(err.message)); // => 'rounds must be a number' ``` -------------------------------- ### Async/Await for Password Checking Source: https://github.com/kelektiv/node.bcrypt.js/blob/master/README.md Demonstrates using async/await with bcrypt.compare for checking user passwords after fetching user data. ```javascript async function checkUser(username, password) { //... fetch user from a db etc. const match = await bcrypt.compare(password, user.passwordHash); if(match) { //login } //... } ``` -------------------------------- ### Hashing Passwords (Async) Source: https://github.com/kelektiv/node.bcrypt.js/blob/master/README.md Demonstrates two techniques for hashing passwords asynchronously using bcrypt.js. Technique 1 involves generating a salt separately, while Technique 2 auto-generates a salt. ```APIDOC ## Hashing Passwords (Async) ### Technique 1: Generate salt and hash separately ```javascript bcrypt.genSalt(saltRounds, function(err, salt) { bcrypt.hash(myPlaintextPassword, salt, function(err, hash) { // Store hash in your password DB. }); }); ``` ### Technique 2: Auto-generate salt and hash ```javascript bcrypt.hash(myPlaintextPassword, saltRounds, function(err, hash) { // Store hash in your password DB. }); ``` ``` -------------------------------- ### Hashing Passwords (Promises) Source: https://github.com/kelektiv/node.bcrypt.js/blob/master/README.md Illustrates hashing a password using the Promise-based API of bcrypt.js, which is compatible with async/await. ```APIDOC ## Hashing Passwords (Promises) ```javascript bcrypt.hash(myPlaintextPassword, saltRounds).then(function(hash) { // Store hash in your password DB. }); ``` ``` -------------------------------- ### Checking Passwords (Sync) Source: https://github.com/kelektiv/node.bcrypt.js/blob/master/README.md Demonstrates how to synchronously compare a plaintext password against a stored hash using bcrypt.js. ```APIDOC ## Checking Passwords (Sync) ```javascript // Load hash from your password DB. bcrypt.compareSync(myPlaintextPassword, hash); // true bcrypt.compareSync(someOtherPlaintextPassword, hash); // false ``` ``` -------------------------------- ### Checking Passwords (Async) Source: https://github.com/kelektiv/node.bcrypt.js/blob/master/README.md Shows how to compare a plaintext password against a stored hash asynchronously using bcrypt.js. ```APIDOC ## Checking Passwords (Async) ```javascript // Load hash from your password DB. bcrypt.compare(myPlaintextPassword, hash, function(err, result) { // result == true }); bcrypt.compare(someOtherPlaintextPassword, hash, function(err, result) { // result == false }); ``` ``` -------------------------------- ### Swap Promise Implementation Source: https://context7.com/kelektiv/node.bcrypt.js/llms.txt Use `bcrypt.promises.use` to replace the default Promise constructor with a custom one, such as Bluebird. This allows integration with libraries offering advanced Promise features. Reset to the native Promise implementation using `global.Promise`. ```javascript const bcrypt = require('bcrypt'); const bluebird = require('bluebird'); // Switch to Bluebird for all bcrypt async operations bcrypt.promises.use(bluebird); // All promise-returning methods now return Bluebird promises const saltPromise = bcrypt.genSalt(10); console.log(saltPromise instanceof bluebird); // true saltPromise .then(salt => bcrypt.hash('password', salt)) .then(hash => console.log('Hash with Bluebird:', hash)) .catch(err => console.error('Error:', err.message)); // Reset to native Promise bcrypt.promises.use(global.Promise); const nativeSalt = bcrypt.genSalt(10); console.log(nativeSalt instanceof Promise); // true // ESM import style (compatible with all async methods above) import bcrypt from 'bcrypt'; const hash = await bcrypt.hash('myPassword', 10); console.log(hash); // '$2b$10$...' ``` -------------------------------- ### Checking Passwords (Promises) Source: https://github.com/kelektiv/node.bcrypt.js/blob/master/README.md Demonstrates comparing a password against a hash using the Promise-based API of bcrypt.js, suitable for use with async/await. ```APIDOC ## Checking Passwords (Promises) ```javascript // Load hash from your password DB. bcrypt.compare(myPlaintextPassword, hash).then(function(result) { // result == true }); bcrypt.compare(someOtherPlaintextPassword, hash).then(function(result) { // result == false }); ``` ``` -------------------------------- ### ESM Import Usage Source: https://github.com/kelektiv/node.bcrypt.js/blob/master/README.md Shows how to import and use bcrypt.js with ECMAScript Modules (ESM). ```APIDOC ## ESM import ```javascript import bcrypt from "bcrypt"; // later await bcrypt.compare(password, hash); ``` ``` -------------------------------- ### Generate Salt Asynchronously with Callbacks Source: https://context7.com/kelektiv/node.bcrypt.js/llms.txt This callback-style asynchronous method is suitable for generating bcrypt salts when not using Promises. Ensure error handling for the callback. ```javascript // --- Callback style --- bcrypt.genSalt(12, function(err, salt) { if (err) throw err; console.log('Salt (12 rounds):', salt); }); ``` -------------------------------- ### Generate Legacy $2a$ Salt Asynchronously Source: https://context7.com/kelektiv/node.bcrypt.js/llms.txt Generate a salt with the legacy '$2a$' prefix by specifying 'a' as the minor version. This is useful for compatibility with older bcrypt implementations. ```javascript // --- With minor version 'a' --- bcrypt.genSalt(10, 'a', function(err, salt) { if (err) throw err; // salt starts with '$2a$10$' console.log('Legacy $2a$ salt:', salt); }); ``` -------------------------------- ### bcrypt.hash(data, salt, cb?) Source: https://context7.com/kelektiv/node.bcrypt.js/llms.txt Hashes data asynchronously using a specified salt or auto-generates a salt based on rounds. This is the recommended method for server environments as it utilizes a thread pool to avoid blocking the event loop. It can be used with Promises or callbacks. ```APIDOC ## `bcrypt.hash(data, salt, cb?)` — Hash data asynchronously Hashes `data` (string or Buffer) with the provided `salt`. If `salt` is a number, it is treated as a round count and a salt is auto-generated internally. Omitting `cb` returns a Promise. This is the **recommended** API for server environments as it runs in a thread pool without blocking the event loop. ### Parameters #### Path Parameters - **data** (string | Buffer) - Required - The data to hash. - **salt** (number | string) - Required - If a number, it's the salt rounds. If a string, it's a pre-generated salt. - **cb** (function) - Optional - Callback function that receives an error and the hash. ### Request Example (Promise) ```javascript const bcrypt = require('bcrypt'); async function hashPassword(password) { const salt = await bcrypt.genSalt(10); const hash = await bcrypt.hash(password, salt); return hash; } // Or with auto-salt generation: async function hashPasswordAutoSalt(password) { const hash = await bcrypt.hash(password, 10); return hash; } ``` ### Request Example (Callback) ```javascript const bcrypt = require('bcrypt'); bcrypt.hash('s0/\/\P4$$w0rD', 10, function(err, hash) { if (err) throw err; console.log('Stored hash:', hash); }); ``` ### Response (Promise) - Returns a Promise that resolves with the hash string. ### Response (Callback) - `err` (Error) - If an error occurred. - `hash` (string) - The generated hash string. ``` -------------------------------- ### bcrypt.promises.use(promiseImplementation) Source: https://context7.com/kelektiv/node.bcrypt.js/llms.txt Allows swapping the Promise constructor used internally by all asynchronous bcrypt methods. This is useful for integrating with alternative Promise libraries like Bluebird. ```APIDOC ## `bcrypt.promises.use(promiseImplementation)` — Swap the Promise implementation ### Description Replaces the Promise constructor used internally by all async bcrypt methods. By default, `global.Promise` (native Node.js Promises) is used. This is useful for integrating with libraries like Bluebird that offer richer debugging, cancellation, or performance characteristics. ### Parameters #### Path Parameters - **promiseImplementation** (PromiseConstructor) - Required - The Promise constructor to use (e.g., `bluebird`, `global.Promise`). ### Request Example ```javascript const bcrypt = require('bcrypt'); const bluebird = require('bluebird'); // Switch to Bluebird for all bcrypt async operations bcrypt.promises.use(bluebird); // All promise-returning methods now return Bluebird promises const saltPromise = bcrypt.genSalt(10); console.log(saltPromise instanceof bluebird); // true saltPromise .then(salt => bcrypt.hash('password', salt)) .then(hash => console.log('Hash with Bluebird:', hash)) .catch(err => console.error('Error:', err.message)); // Reset to native Promise bcrypt.promises.use(global.Promise); const nativeSalt = bcrypt.genSalt(10); console.log(nativeSalt instanceof Promise); // true // ESM import style (compatible with all async methods above) import bcrypt from 'bcrypt'; const hash = await bcrypt.hash('myPassword', 10); console.log(hash); // '$2b$10$...' ``` ### Response This method does not return a value. It modifies the internal Promise implementation used by the library. ``` -------------------------------- ### Generate Salt Asynchronously with Promises Source: https://context7.com/kelektiv/node.bcrypt.js/llms.txt Use this method with async/await for generating a bcrypt salt. The 'rounds' parameter controls the computational cost, and 'minor' selects the bcrypt version prefix. ```javascript const bcrypt = require('bcrypt'); // --- Promise / async-await --- async function registerUser(plainPassword) { // 10 rounds ≈ 10 hashes/sec on a 2GHz core; increase for higher security const salt = await bcrypt.genSalt(10); // salt => '$2b$10$nOUIs5kJ7naTuTFkBy1veu' (29 chars, includes version + rounds) console.log('Generated salt:', salt); const hash = await bcrypt.hash(plainPassword, salt); console.log('Hash:', hash); // => '$2b$10$nOUIs5kJ7naTuTFkBy1veuK0kSxUFXfuaOKdOKf9xYT0KKIGSJwFa' return hash; } ``` -------------------------------- ### Synchronous Hashing with bcrypt.js Source: https://context7.com/kelektiv/node.bcrypt.js/llms.txt Use this for synchronous hashing when blocking the event loop is acceptable. Avoid in HTTP servers or concurrent environments. Supports Buffer input and explicit/auto salt generation. ```javascript const bcrypt = require('bcrypt'); // Auto-generate salt and hash in one call const hash = bcrypt.hashSync('myPassword', 10); console.log(hash); // => '$2b$10$...' (60 characters) // Two-step with explicit salt const salt = bcrypt.genSaltSync(12); const hash2 = bcrypt.hashSync('myPassword', salt); console.log(bcrypt.getRounds(hash2)); // 12 // Accepts Buffer input const bufHash = bcrypt.hashSync(Buffer.from('bufferpass'), 10); console.log(typeof bufHash); // 'string' // Error cases try { bcrypt.hashSync(); // => 'data and salt arguments required' } catch (e) { console.error(e.message); } try { bcrypt.hashSync('password'); // => 'data and salt arguments required' } catch (e) { console.error(e.message); } try { bcrypt.hashSync('password', {}); // => 'data must be a string or Buffer...' } catch (e) { console.error(e.message); } ``` -------------------------------- ### Asynchronous Hashing with bcrypt.js Source: https://context7.com/kelektiv/node.bcrypt.js/llms.txt Use this API in server environments for non-blocking hashing. It supports both explicit salt generation and auto-generation of salts. Can be used with async/await or callbacks. ```javascript const bcrypt = require('bcrypt'); // Technique 1: explicit salt (two-step) async function hashWithExplicitSalt(password) { const salt = await bcrypt.genSalt(10); const hash = await bcrypt.hash(password, salt); // Store `hash` in your database — never store the plain password return hash; } // Technique 2: auto-salt (one-step) — identical result async function hashAutoSalt(password) { const hash = await bcrypt.hash(password, 10); // 10 = saltRounds return hash; } // Callback stylecrypt.hash('s0/\/\P4$$w0rD', 10, function(err, hash) { if (err) throw err; // hash => '$2b$10$...' (60 characters) console.log('Stored hash:', hash); }); // Hashing a Buffer (e.g., binary data) const buf = Buffer.from('binarypassword'); bcrypt.hash(buf, 10).then(hash => console.log('Buffer hash:', hash)); // Error: missing arguments bcrypt.hash().catch(err => console.error(err.message)); // => 'data and salt arguments required' bcrypt.hash('password', 'some$value').catch(err => console.error(err.message)); // => 'Invalid salt. Salt must be in the form of: $Vers$log2(NumRounds)$saltvalue' ``` -------------------------------- ### Generate Salt Synchronously Source: https://context7.com/kelektiv/node.bcrypt.js/llms.txt Use `genSaltSync` for synchronous salt generation in scripts or CLI tools. Avoid this in server request handlers as it blocks the event loop. ```javascript const bcrypt = require('bcrypt'); // Default 10 rounds, minor 'b' const salt = bcrypt.genSaltSync(); // => '$2b$10$...' (29 characters) // Custom rounds const saltHigh = bcrypt.genSaltSync(13); const [, version, rounds] = saltHigh.split('$'); console.log(version); // '2b' console.log(rounds); // '13' // Legacy $2a$ prefix const saltLegacy = bcrypt.genSaltSync(10, 'a'); console.log(saltLegacy.startsWith('$2a$')); // true ``` -------------------------------- ### Use Promises for Hashing Source: https://github.com/kelektiv/node.bcrypt.js/blob/master/README.md Leverage the promise-based API for asynchronous password hashing. This is compatible with async/await syntax. ```javascript const bluebird = require('bluebird'); bcrypt.promises.use(bluebird); ``` ```javascript bcrypt.hash(myPlaintextPassword, saltRounds).then(function(hash) { // Store hash in your password DB. }); ``` -------------------------------- ### bcrypt.genSaltSync(rounds?, minor?) Source: https://context7.com/kelektiv/node.bcrypt.js/llms.txt Synchronous counterpart to `genSalt`. Blocks the event loop until salt generation completes. Suitable only for scripts, CLI tools, or application startup code — not for use inside request handlers. ```APIDOC ## bcrypt.genSaltSync(rounds?, minor?) ### Description Synchronous counterpart to `genSalt`. Blocks the event loop until salt generation completes. Suitable only for scripts, CLI tools, or application startup code — **not** for use inside request handlers. ### Method Synchronous ### Parameters #### Optional Parameters - **rounds** (number) - The cost factor for hashing. Defaults to 10. Clamped between 4 and 31. - **minor** (string) - The bcrypt version prefix. Accepts 'b' (default, `$2b$`) or 'a' (`$2a$`). ### Request Example ```javascript // Default 10 rounds, minor 'b' const salt = bcrypt.genSaltSync(); // Custom rounds const saltHigh = bcrypt.genSaltSync(13); // Legacy $2a$ prefix const saltLegacy = bcrypt.genSaltSync(10, 'a'); // Error cases try { bcrypt.genSaltSync('10'); // throws: rounds must be a number } catch (err) { console.error(err.message); } try { bcrypt.genSaltSync(10, 'c'); // throws: minor must be either "a" or "b" } catch (err) { console.error(err.message); } ``` ### Response #### Success Response - **salt** (string) - The generated bcrypt salt string (e.g., '$2b$10$nOUIs5kJ7naTuTFkBy1veu'). #### Error Response - **Error** - Throws an error if `rounds` is not a number or `minor` is invalid. ``` -------------------------------- ### Utility Functions Source: https://github.com/kelektiv/node.bcrypt.js/blob/master/README.md Provides utility functions for extracting information from hashes and managing promise implementations. ```APIDOC ## getRounds ### Description Extracts the number of rounds used to encrypt a given hash. ### Method `BCrypt.getRounds(encrypted)` ### Parameters #### Path Parameters - **encrypted** (string) - Required - The hash from which to extract the number of rounds. ## promises.use ### Description Changes the Promise implementation used by bcrypt. ### Method `BCrypt.promises.use(promiseImplementation)` ### Parameters #### Path Parameters - **promiseImplementation** (object) - Required - A Promises/A+ compatible implementation to be used. ``` -------------------------------- ### bcrypt.genSalt(rounds?, minor?, cb?) Source: https://context7.com/kelektiv/node.bcrypt.js/llms.txt Generates a cryptographically random bcrypt salt string asynchronously. `rounds` controls the cost factor (default 10), and `minor` selects the bcrypt version prefix ('b' or 'a'). Omitting `cb` returns a Promise. Salt values are clamped between 4 and 31 rounds. ```APIDOC ## bcrypt.genSalt(rounds?, minor?, cb?) ### Description Generates a cryptographically random bcrypt salt string asynchronously. `rounds` controls the cost factor (default 10), and `minor` selects the bcrypt version prefix ('b' or 'a'). Omitting `cb` returns a Promise. Salt values are clamped between 4 and 31 rounds. ### Method Asynchronous (Callback or Promise) ### Parameters #### Optional Parameters - **rounds** (number) - The cost factor for hashing. Defaults to 10. Clamped between 4 and 31. - **minor** (string) - The bcrypt version prefix. Accepts 'b' (default, `$2b$`) or 'a' (`$2a$`). - **cb** (function) - A callback function `(err, salt) => {}`. ### Request Example ```javascript // Promise / async-await async function registerUser(plainPassword) { const salt = await bcrypt.genSalt(10); const hash = await bcrypt.hash(plainPassword, salt); return hash; } // Callback style bcrypt.genSalt(12, function(err, salt) { if (err) throw err; console.log('Salt (12 rounds):', salt); }); // With minor version 'a' bcrypt.genSalt(10, 'a', function(err, salt) { if (err) throw err; console.log('Legacy $2a$ salt:', salt); }); // Error handling bcrypt.genSalt('10').catch(err => console.error(err.message)); ``` ### Response #### Success Response - **salt** (string) - The generated bcrypt salt string (e.g., '$2b$10$nOUIs5kJ7naTuTFkBy1veu'). #### Error Response - **Error** - Throws an error if `rounds` is not a number. ``` -------------------------------- ### Use Promises for Checking Passwords Source: https://github.com/kelektiv/node.bcrypt.js/blob/master/README.md Leverage the promise-based API for asynchronous password comparison. This is compatible with async/await syntax. ```javascript // Load hash from your password DB. bcrypt.compare(myPlaintextPassword, hash).then(function(result) { // result == true }); bcrypt.compare(someOtherPlaintextPassword, hash).then(function(result) { // result == false }); ``` -------------------------------- ### Hash Password Asynchronously (Recommended) Source: https://github.com/kelektiv/node.bcrypt.js/blob/master/README.md Use the asynchronous API to hash a password. This method is recommended for server environments to prevent blocking the event loop. It can generate a salt and hash in separate calls or in a single call. ```javascript const bcrypt = require('bcrypt'); const saltRounds = 10; const myPlaintextPassword = 's0/\/\/P4$$w0rD'; const someOtherPlaintextPassword = 'not_bacon'; ``` ```javascript bcrypt.genSalt(saltRounds, function(err, salt) { bcrypt.hash(myPlaintextPassword, salt, function(err, hash) { // Store hash in your password DB. }); }); ``` ```javascript bcrypt.hash(myPlaintextPassword, saltRounds, function(err, hash) { // Store hash in your password DB. }); ``` -------------------------------- ### bcrypt.compare(data, hash, cb?) Source: https://context7.com/kelektiv/node.bcrypt.js/llms.txt Compares plaintext data against a stored bcrypt hash asynchronously. Returns true if they match, false otherwise. This comparison is resistant to timing attacks. It can be used with Promises or callbacks. ```APIDOC ## `bcrypt.compare(data, hash, cb?)` — Verify a password asynchronously Compares plaintext `data` against a stored bcrypt `hash`. Returns `true` if they match, `false` otherwise. Omitting `cb` returns a Promise. The comparison is performed against the full bcrypt digest (not raw passwords), making it resistant to timing attacks based on preimage resistance — an attacker cannot gain information about the stored hash from comparison timing. ### Parameters #### Path Parameters - **data** (string | Buffer) - Required - The plaintext data to compare. - **hash** (string) - Required - The stored bcrypt hash. - **cb** (function) - Optional - Callback function that receives an error and a boolean result. ### Request Example (Promise) ```javascript const bcrypt = require('bcrypt'); async function verifyPassword(plaintextPassword, user) { const match = await bcrypt.compare(plaintextPassword, user.passwordHash); return match; } ``` ### Request Example (Callback) ```javascript const bcrypt = require('bcrypt'); bcrypt.compare('testPassword', storedHash, function(err, result) { if (err) throw err; if (result) { console.log('Access granted'); } else { console.log('Access denied'); } }); ``` ### Response (Promise) - Returns a Promise that resolves with a boolean: `true` if the data matches the hash, `false` otherwise. ### Response (Callback) - `err` (Error) - If an error occurred. - `result` (boolean) - `true` if the data matches the hash, `false` otherwise. ``` -------------------------------- ### Configure npm for root execution on AWS Elastic Beanstalk Source: https://github.com/kelektiv/node.bcrypt.js/wiki/Installation-Instructions This configuration file forces npm to run node-gyp as root, resolving permission denied errors during deployment on AWS Elastic Beanstalk with npm@5 or @6. ```ini # Force npm to run node-gyp also as root, preventing permission denied errors in AWS with npm@5 or @6 unsafe-perm=true ``` -------------------------------- ### bcrypt.compareSync(data, hash) Source: https://context7.com/kelektiv/node.bcrypt.js/llms.txt Synchronously verifies if the provided data matches the given hash. This method blocks the event loop and should only be used in non-concurrent contexts like scripts or CLI tools. It returns a boolean indicating whether the data matches the hash. Invalid inputs like empty strings or null hashes will return false without throwing errors. ```APIDOC ## `bcrypt.compareSync(data, hash)` — Verify a password synchronously ### Description Synchronous counterpart to `compare`. Returns a boolean directly. Blocks the event loop — use only in non-concurrent contexts such as scripts or CLI tools. ### Parameters #### Path Parameters - **data** (string) - Required - The plaintext data to compare. - **hash** (string) - Required - The hash to compare against. ### Request Example ```javascript const bcrypt = require('bcrypt'); const hash = bcrypt.hashSync('mySecret', 10); // Correct password const match = bcrypt.compareSync('mySecret', hash); console.log(match); // true // Wrong password const noMatch = bcrypt.compareSync('wrongPassword', hash); console.log(noMatch); // false // Empty and invalid inputs always return false (never throw) console.log(bcrypt.compareSync('', hash)); // false console.log(bcrypt.compareSync('', '')); // false console.log(bcrypt.compareSync('password', '')); // false // Known hash from test suite const knownHash = '$2a$10$XOPbrlUPQdwdJUpSrIF6X.LbE14qsMmKGhM1A8W9iqaG3vv1BD7WC'; console.log(bcrypt.compareSync('envy1362987212538', knownHash)); // true console.log(bcrypt.compareSync('envy1362987212538', ':')); // false // Error case: missing arguments try { bcrypt.compareSync(); } catch (e) { console.error(e.message); // 'data and hash arguments required' } ``` ### Response #### Success Response (boolean) - **match** (boolean) - `true` if the data matches the hash, `false` otherwise. ``` -------------------------------- ### Asynchronous Password Verification with bcrypt.js Source: https://context7.com/kelektiv/node.bcrypt.js/llms.txt Compares a plaintext password against a stored bcrypt hash. Returns a Promise or uses a callback. This method is resistant to timing attacks. ```javascript const bcrypt = require('bcrypt'); // --- async/await login handler --- async function login(username, plaintextPassword, db) { const user = await db.findUser(username); if (!user) return { success: false, reason: 'user not found' }; const match = await bcrypt.compare(plaintextPassword, user.passwordHash); if (match) { return { success: true, user }; } return { success: false, reason: 'invalid password' }; } // --- Standalone examples --- (async () => { const hash = await bcrypt.hash('s0/\/\P4$$w0rD', 10); const correct = await bcrypt.compare('s0/\/\P4$$w0rD', hash); console.log('Correct password:', correct); // true const wrong = await bcrypt.compare('not_bacon', hash); console.log('Wrong password:', wrong); // false const empty = await bcrypt.compare('', hash); console.log('Empty password:', empty); // false })(); // --- Callback style --- bcrypt.compare('testPassword', storedHash, function(err, result) { if (err) throw err; if (result) { console.log('Access granted'); } else { console.log('Access denied'); } }); // Error: missing arguments bcrypt.compare().catch(err => console.error(err.message)); // => 'data and hash arguments required' ``` -------------------------------- ### bcrypt Hash Format Reference Source: https://context7.com/kelektiv/node.bcrypt.js/llms.txt Reference for the structure of a bcrypt hash, detailing the algorithm identifier, cost factor, salt, and hash value components, along with the character set used. ```plaintext $2b$10$nOUIs5kJ7naTuTFkBy1veuK0kSxUFXfuaOKdOKf9xYT0KKIGSJwFa | | | | | | salt (22 chars) hash value (31 chars) | cost factor (10 = 2^10 iterations) algorithm ($2b$ = BCrypt, $2a$ = legacy BCrypt) Total: 60 characters Character set: ./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789$ ``` -------------------------------- ### Handle Invalid Inputs for genSaltSync Source: https://context7.com/kelektiv/node.bcrypt.js/llms.txt Demonstrates error handling for `bcrypt.genSaltSync` with invalid 'rounds' or 'minor' parameters. 'rounds' must be a number, and 'minor' must be 'a' or 'b'. ```javascript // Error cases try { bcrypt.genSaltSync('10'); // throws: rounds must be a number } catch (err) { console.error(err.message); } try { bcrypt.genSaltSync(10, 'c'); // throws: minor must be either "a" or "b" } catch (err) { console.error(err.message); } ``` -------------------------------- ### bcrypt.hashSync(data, salt) Source: https://context7.com/kelektiv/node.bcrypt.js/llms.txt Synchronously hashes data using a specified salt or auto-generates a salt. This method blocks the Node.js event loop and should be avoided in concurrent environments like HTTP servers. ```APIDOC ## `bcrypt.hashSync(data, salt)` — Hash data synchronously Synchronous version of `hash`. Accepts the same arguments and returns the hash string directly. Blocks the Node.js event loop for the full duration of the hashing operation — avoid in HTTP servers or any concurrent environment. ### Parameters #### Path Parameters - **data** (string | Buffer) - Required - The data to hash. - **salt** (number | string) - Required - If a number, it's the salt rounds. If a string, it's a pre-generated salt. ### Request Example ```javascript const bcrypt = require('bcrypt'); // Auto-generate salt and hash in one call const hash = bcrypt.hashSync('myPassword', 10); console.log(hash); // Two-step with explicit salt const salt = bcrypt.genSaltSync(12); const hash2 = bcrypt.hashSync('myPassword', salt); ``` ### Response - Returns the generated hash string. ``` -------------------------------- ### Synchronously Compare Password with Hash Source: https://context7.com/kelektiv/node.bcrypt.js/llms.txt Use `compareSync` for synchronous password verification. It blocks the event loop, so it's suitable only for non-concurrent contexts like scripts or CLI tools. It returns a boolean and never throws errors for invalid inputs, always returning false. ```javascript const bcrypt = require('bcrypt'); const hash = bcrypt.hashSync('mySecret', 10); // Correct password const match = bcrypt.compareSync('mySecret', hash); console.log(match); // true // Wrong password const noMatch = bcrypt.compareSync('wrongPassword', hash); console.log(noMatch); // false // Empty and invalid inputs always return false (never throw) console.log(bcrypt.compareSync('', hash)); // false console.log(bcrypt.compareSync('', '')); // false console.log(bcrypt.compareSync('password', '')); // false // Known hash from test suite const knownHash = '$2a$10$XOPbrlUPQdwdJUpSrIF6X.LbE14qsMmKGhM1A8W9iqaG3vv1BD7WC'; console.log(bcrypt.compareSync('envy1362987212538', knownHash)); // true console.log(bcrypt.compareSync('envy1362987212538', ':')); // false // Error case: missing arguments try { bcrypt.compareSync(); } catch (e) { console.error(e.message); // 'data and hash arguments required' } ``` -------------------------------- ### Salt Generation Source: https://github.com/kelektiv/node.bcrypt.js/blob/master/README.md Generates a salt for bcrypt hashing. Supports both synchronous and asynchronous operations. ```APIDOC ## genSaltSync ### Description Generates a salt synchronously. ### Method `BCrypt.genSaltSync(rounds, minor)` ### Parameters #### Path Parameters - **rounds** (number) - Optional - The cost of processing the data. Defaults to 10. - **minor** (string) - Optional - The minor version of bcrypt to use. Defaults to 'b'. ## genSalt ### Description Generates a salt asynchronously. ### Method `BCrypt.genSalt(rounds, minor, cb)` ### Parameters #### Path Parameters - **rounds** (number) - Optional - The cost of processing the data. Defaults to 10. - **minor** (string) - Optional - The minor version of bcrypt to use. Defaults to 'b'. - **cb** (function) - Optional - A callback function to be fired once the salt has been generated. If not specified, a Promise is returned. - **err** (Error) - First parameter to the callback detailing any errors. - **salt** (string) - Second parameter to the callback providing the generated salt. ``` -------------------------------- ### Password Comparison Source: https://github.com/kelektiv/node.bcrypt.js/blob/master/README.md Compares data against an encrypted hash. Supports both synchronous and asynchronous operations. ```APIDOC ## compareSync ### Description Compares data against an encrypted hash synchronously. ### Method `BCrypt.compareSync(data, encrypted)` ### Parameters #### Path Parameters - **data** (string | Buffer) - Required - Data to compare. - **encrypted** (string) - Required - Data to be compared to. ## compare ### Description Compares data against an encrypted hash asynchronously. ### Method `BCrypt.compare(data, encrypted, cb)` ### Parameters #### Path Parameters - **data** (string | Buffer) - Required - Data to compare. - **encrypted** (string) - Required - Data to be compared to. - **cb** (function) - Optional - A callback function to be fired once the data has been compared. If not specified, a Promise is returned. - **err** (Error) - First parameter to the callback detailing any errors. - **same** (boolean) - Second parameter to the callback providing whether the data and encrypted forms match. ``` -------------------------------- ### Check Password Asynchronously (Recommended) Source: https://github.com/kelektiv/node.bcrypt.js/blob/master/README.md Use the asynchronous API to compare a plaintext password against a stored hash. This method returns a boolean indicating whether the password matches the hash. ```javascript // Load hash from your password DB. bcrypt.compare(myPlaintextPassword, hash, function(err, result) { // result == true }); bcrypt.compare(someOtherPlaintextPassword, hash, function(err, result) { // result == false }); ``` -------------------------------- ### Extract Cost Factor from Hash Source: https://context7.com/kelektiv/node.bcrypt.js/llms.txt Use `getRounds` to parse the cost factor from a bcrypt hash. This is useful for implementing re-hashing strategies to upgrade older, weaker hashes to a stronger cost factor over time. The function expects a string hash and throws errors for invalid or missing inputs. ```javascript const bcrypt = require('bcrypt'); const CURRENT_ROUNDS = 12; // Inspect existing hash const hash = bcrypt.hashSync('password', 10); const rounds = bcrypt.getRounds(hash); console.log(rounds); // 10 // Re-hash pattern: upgrade weak hashes on successful login async function loginWithRehash(plainPassword, storedHash, db, userId) { const match = await bcrypt.compare(plainPassword, storedHash); if (!match) return false; const usedRounds = bcrypt.getRounds(storedHash); if (usedRounds < CURRENT_ROUNDS) { // Silently upgrade the hash in the background const newHash = await bcrypt.hash(plainPassword, CURRENT_ROUNDS); await db.updatePasswordHash(userId, newHash); console.log(`Upgraded hash from ${usedRounds} to ${CURRENT_ROUNDS} rounds`); } return true; } // Async hash round extraction bcrypt.hash('bacon', 8).then(hash => { console.log(bcrypt.getRounds(hash)); // 8 }); // Error cases try { bcrypt.getRounds(''); // throws: 'invalid hash provided' } catch (e) { console.error(e.message); } try { bcrypt.getRounds(null); // throws: 'hash argument required' } catch (e) { console.error(e.message); } try { bcrypt.getRounds(12345); // throws: 'hash must be a string' } catch (e) { console.error(e.message); } ``` -------------------------------- ### Hash Password Synchronously Source: https://github.com/kelektiv/node.bcrypt.js/blob/master/README.md Use the synchronous API to hash a password. This method is generally not recommended for server applications as it can block the event loop. ```javascript const bcrypt = require('bcrypt'); const saltRounds = 10; const myPlaintextPassword = 's0/\/\/P4$$w0rD'; const someOtherPlaintextPassword = 'not_bacon'; ``` ```javascript const salt = bcrypt.genSaltSync(saltRounds); const hash = bcrypt.hashSync(myPlaintextPassword, salt); // Store hash in your password DB. ``` ```javascript const hash = bcrypt.hashSync(myPlaintextPassword, saltRounds); // Store hash in your password DB. ``` -------------------------------- ### Password Hashing Source: https://github.com/kelektiv/node.bcrypt.js/blob/master/README.md Hashes data using bcrypt. Supports both synchronous and asynchronous operations. ```APIDOC ## hashSync ### Description Hashes data synchronously. ### Method `BCrypt.hashSync(data, salt)` ### Parameters #### Path Parameters - **data** (string | Buffer) - Required - The data to be encrypted. - **salt** (string | number) - Required - The salt to be used for hashing. If a number is provided, a salt will be generated with that number of rounds. ## hash ### Description Hashes data asynchronously. ### Method `BCrypt.hash(data, salt, cb)` ### Parameters #### Path Parameters - **data** (string | Buffer) - Required - The data to be encrypted. - **salt** (string | number) - Required - The salt to be used for hashing. If a number is provided, a salt will be generated with that number of rounds. - **cb** (function) - Optional - A callback function to be fired once the data has been encrypted. If not specified, a Promise is returned. - **err** (Error) - First parameter to the callback detailing any errors. - **encrypted** (string) - Second parameter to the callback providing the encrypted form. ``` -------------------------------- ### bcrypt.getRounds(hash) Source: https://context7.com/kelektiv/node.bcrypt.js/llms.txt Extracts the cost factor (number of rounds) from a given bcrypt hash. This is useful for determining the computational effort used to generate the hash, which can inform strategies for re-hashing with updated cost factors. ```APIDOC ## `bcrypt.getRounds(hash)` — Extract cost factor from a hash ### Description Parses the cost factor (number of rounds) that was used when the given hash was generated. Useful for implementing a re-hashing strategy when your application's target cost factor increases over time. ### Parameters #### Path Parameters - **hash** (string) - Required - The bcrypt hash string from which to extract the rounds. ### Request Example ```javascript const bcrypt = require('bcrypt'); const CURRENT_ROUNDS = 12; // Inspect existing hash const hash = bcrypt.hashSync('password', 10); const rounds = bcrypt.getRounds(hash); console.log(rounds); // 10 // Re-hash pattern: upgrade weak hashes on successful login async function loginWithRehash(plainPassword, storedHash, db, userId) { const match = await bcrypt.compare(plainPassword, storedHash); if (!match) return false; const usedRounds = bcrypt.getRounds(storedHash); if (usedRounds < CURRENT_ROUNDS) { // Silently upgrade the hash in the background const newHash = await bcrypt.hash(plainPassword, CURRENT_ROUNDS); await db.updatePasswordHash(userId, newHash); console.log(`Upgraded hash from ${usedRounds} to ${CURRENT_ROUNDS} rounds`); } return true; } // Async hash round extraction bcrypt.hash('bacon', 8).then(hash => { console.log(bcrypt.getRounds(hash)); // 8 }); // Error cases try { bcrypt.getRounds(''); // throws: 'invalid hash provided' } catch (e) { console.error(e.message); } try { bcrypt.getRounds(null); // throws: 'hash argument required' } catch (e) { console.error(e.message); } try { bcrypt.getRounds(12345); // throws: 'hash must be a string' } catch (e) { console.error(e.message); } ``` ### Response #### Success Response (number) - **rounds** (number) - The cost factor (number of rounds) used to generate the hash. ``` -------------------------------- ### Check Password Synchronously Source: https://github.com/kelektiv/node.bcrypt.js/blob/master/README.md Use the synchronous API to compare a plaintext password against a stored hash. This method returns a boolean indicating whether the password matches the hash. ```javascript // Load hash from your password DB. bcrypt.compareSync(myPlaintextPassword, hash); // true bcrypt.compareSync(someOtherPlaintextPassword, hash); // false ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.