node.bcrypt.js

GitHub

bcrypt for NodeJs

7,797 stars C++ #bcrypt
RAW Doc

CHANGELOG

6.0.0 (2025-02-28)


* Drop support for NodeJS <= 16
* Remove node-pre-gyp in favor of prebuildify, prebuilt binaries are now shipped with the package
* Update node-addon-api to 8.3.0
* Update JS code to newer ES syntax

5.1.1 (2022-10-06)


* Update node-pre-gyp to 1.0.11

5.1.0 (2022-10-06)


* Update node-pre-gyp to 1.0.10
* Replace nodeunit with jest as the testing library

5.0.1 (2021-02-22)

* Update node-pre-gyp to 1.0.0

5.0.0 (2020-06-02)

* Fix the bcrypt "wrap-around" bug. It affects passwords with lengths >= 255.
It is uncommon but it's a bug nevertheless. Previous attempts to fix the bug
was unsuccessful.
* Experimental support for z/OS
* Fix a bug related to NUL in password input
* Update node-pre-gyp to 0.15.0

4.0.1 (2020-02-27)

* Fix compilation errors in Alpine linux

4.0.0 (2020-02-17)

* Switch to NAPI bcrypt
* Drop support for NodeJS 8

3.0.8 (2019-12-31)

* Update node-pre-gyp to 0.14
* Pre-built binaries for NodeJS 13

3.0.7 (2019-10-18)

* Update nan to 2.14.0
* Update node-pre-gyp to 0.13

3.0.6 (2019-04-11)

* Update nan to 2.13.2

3.0.5 (2019-03-19)

* Update nan to 2.13.1
* NodeJS 12 compatibility
* Remove node-pre-gyp from bundled dependencies

3.0.4-napi (2019-03-08)

* Sync N-API bcrypt with NAN bcrypt

3.0.4 (2019-02-07)

* Fix GCC, NAN and V8 deprecation warnings

3.0.3 (2018-12-19)

* Update nan to 2.12.1

3.0.2 (2018-10-18)

* Update nan to 2.11.1

3.0.1 (2018-09-20)

* Update nan to 2.11.0

3.0.0 (2018-07-06)

* Drop support for NodeJS <= 4

2.0.1 (2018-04-20)

* Update node-pre-gyp to allow downloading prebuilt modules

2.0.0 (2018-04-07)

* Make 2b the default bcrypt version

1.1.0-napi (2018-01-21)

* Initial support for N-API

1.0.3 (2016-08-23)

* update to nan v2.6.2 for NodeJS 8 support
* Fix: use npm scripts instead of node-gyp directly.

1.0.2 (2016-12-31)

* Fix compare promise rejection with invalid arguments

1.0.1 (2016-12-07)

* Fix destructuring imports with promises

1.0.0 (2016-12-04)

* add Promise support (commit 2488473)

0.8.7 (2016-06-09)

* update nan to 2.3.5 for improved node v6 support

0.8.6 (2016-04-20)

* update nan for node v6 support

0.8.5 (2015-08-12)

* update to nan v2 (adds support for iojs 3)

0.8.4 (2015-07-24)

* fix deprecation warning for the Encode API

0.8.3 (2015-05-06)

* update nan to 1.8.4 for iojs 2.x support

0.8.2 (2015-03-28)

* always use callback for generating random bytes to avoid blocking

0.8.1 (2015-01-18)


* update NaN to 1.5.0 for iojs support

0.8.0 (2014-08-03)


* migrate to NAN for bindings

v0.5.0


* Fix for issue around empty string params throwing Errors.
* Method deprecation.
* Upgrade from libeio/ev to libuv. (shtylman)
--- NOTE --- Breaks 0.4.x compatibility
* EV_MULTIPLICITY compile flag.

v0.4.1


* Thread safety fix around OpenSSL (GH-32). (bnoordhuis - through node)
* C++ code changes using delete and new instead of malloc and free. (shtylman)
* Compile options for speed, zoom. (shtylman)
* Move much of the type and variable checking to the JS. (shtylman)

v0.4.0


* Added getRounds function that will tell you the number of rounds within a hash/salt

v0.3.2


* Fix api issue with async salt gen first param

v0.3.1


* Compile under node 0.5.x

v0.3.0


* Internal Refactoring
* Remove pthread dependencies and locking
* Fix compiler warnings and a memory bug

v0.2.4


* Use threadsafe functions instead of pthread mutexes
* salt validation to make sure the salt is of the correct size and format

v0.2.3


* cygwin support

v0.2.2


* Remove dependency on libbsd, use libssl instead

v0.2.0


* Added async functionality
* API changes
* hashpw -> encrypt
* all old sync methods now end with _sync
* Removed libbsd(arc4random) dependency...now uses openssl which is more widely spread

v0.1.2


* Security fix. Wasn't reading rounds in properly and was always only using 4 rounds

---

README

node.bcrypt.js

[](https://github.com/kelektiv/node.bcrypt.js/actions/workflows/ci.yaml)

[](https://ci.appveyor.com/project/defunctzombie/node-bcrypt-js-pgo26/branch/master)

A library to help you hash passwords.

You can read about [bcrypt in Wikipedia][bcryptwiki] as well as in the following article:
[How To Safely Store A Password][codahale]

If You Are Submitting Bugs or Issues

Please verify that the NodeJS version you are using is a _stable_ version; Unstable versions are currently not supported and issues created while using an unstable version will be closed.

If you are on a stable version of NodeJS, please provide a sufficient code snippet or log files for installation issues. The code snippet does not require you to include confidential information. However, it must provide enough information so the problem can be replicable, or it may be closed without an explanation.


Version Compatibility

_Please upgrade to at least v5.0.0 to avoid security issues mentioned below._

| Node Version | Bcrypt Version |
| -------------- | ------------------|
| 0.4 | <= 0.4 |
| 0.6, 0.8, 0.10 | >= 0.5 |
| 0.11 | >= 0.8 |
| 4 | <= 2.1.0 |
| 8 | >= 1.0.3 < 4.0.0 |
| 10, 11 | >= 3 |
| 12 onwards | >= 3.0.6 |
| 18 onwards | >= 6.0.0 |

node-gyp only works with stable/released versions of node. Since the bcrypt module uses node-gyp to build and install, you'll need a stable version of node to use bcrypt. If you do not, you'll likely see an error that starts with:

text
gyp ERR! stack Error: "pre" versions of node cannot be installed, use the --nodedir flag instead

Security Issues And Concerns

Per bcrypt implementation, only the first 72 bytes of a string are used. Any extra bytes are ignored when matching passwords. Note that this is not the first 72 characters. It is possible for a string to contain less than 72 characters, while taking up more than 72 bytes (e.g. a UTF-8 encoded string containing emojis). If a string is provided, it will be encoded using UTF-8.

As should be the case with any security tool, anyone using this library should scrutinise it. If you find or suspect an issue with the code, please bring it to the maintainers' attention. We will spend some time ensuring that this library is as secure as possible.

Here is a list of BCrypt-related security issues/concerns that have come up over the years.

* An [issue with passwords][jtr] was found with a version of the Blowfish algorithm developed for John the Ripper. This is not present in the OpenBSD version and is thus not a problem for this module. HT [zooko][zooko].
* Versions < 5.0.0 suffer from bcrypt wrap-around bug and _will truncate passwords >= 255 characters leading to severely weakened passwords_. Please upgrade at earliest. See [this wiki page][wrap-around-bug] for more details.
* Versions < 5.0.0 _do not handle NUL characters inside passwords properly leading to all subsequent characters being dropped and thus resulting in severely weakened passwords_. Please upgrade at earliest. See [this wiki page][improper-nuls] for more details.

Compatibility Note

This library supports $2a$ and $2b$ prefix bcrypt hashes. $2x$ and $2y$ hashes are specific to bcrypt implementation developed for John the Ripper. In theory, they should be compatible with $2b$ prefix.

Compatibility with hashes generated by other languages is not 100% guaranteed due to difference in character encodings. However, it should not be an issue for most cases.

Migrating from v1.0.x

Hashes generated in earlier version of bcrypt remain 100% supported in v2.x.x and later versions. In most cases, the migration should be a bump in the package.json.

Hashes generated in v2.x.x using the defaults parameters will not work in earlier versions.

Dependencies

* NodeJS
* node-gyp
* Please check the dependencies for this tool at: https://github.com/nodejs/node-gyp
* Windows users will need the options for c# and c++ installed with their visual studio instance.
* Python 2.x/3.x
* OpenSSL - This is only required to build the bcrypt project if you are using versions <= 0.7.7. Otherwise, we're using the builtin node crypto bindings for seed data (which use the same OpenSSL code paths we were, but don't have the external dependency).

Install via NPM

text
npm install bcrypt

Note: OS X users using Xcode 4.3.1 or above may need to run the following command in their terminal prior to installing if errors occur regarding xcodebuild: ``sudo xcode-select -switch /Applications/Xcode.app/Contents/Developer
text
_Pre-built binaries for various NodeJS versions are made available on a best-effort basis._

Only the current stable and supported LTS releases (Node 18+) are actively tested against.

_There may be an interval between the release of the module and the availability of the compiled modules._

Currently, we have pre-built binaries that support the following platforms:

1. Windows x64 and arm64
2. Linux x64 and arm64 (GlibC and musl)
3. macOS x64 and arm64

If you face an error like this:


node-pre-gyp ERR! Tried to download(404): https://github.com/kelektiv/node.bcrypt.js/releases/download/v1.0.2/bcrypt_lib-v1.0.2-node-v48-linux-x64.tar.gz
text
Make sure you have the appropriate dependencies installed and configured for your platform. You can find installation instructions for the dependencies for some common platforms [in this page][depsinstall].

Usage

javascript
const bcrypt = require('bcrypt');
const saltRounds = 10;
const myPlaintextPassword = 's0/\/\P4$$w0rD';
const someOtherPlaintextPassword = 'not_bacon';
text
#### To hash a password:

Technique 1 (generate a salt and hash on separate function calls):

javascript
bcrypt.genSalt(saltRounds, function(err, salt) {
bcrypt.hash(myPlaintextPassword, salt, function(err, hash) {
// Store hash in your password DB.
});
});
text
Technique 2 (auto-gen a salt and hash):
javascript
bcrypt.hash(myPlaintextPassword, saltRounds, function(err, hash) {
// Store hash in your password DB.
});
text
Note that both techniques achieve the same end-result.

#### To check a password:

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
});
text
A Note on Timing Attacks

with promises

bcrypt uses whatever Promise implementation is available in global.Promise. NodeJS has a native Promise implementation built in. However, this should work in any Promises/A+ compliant implementation.

Async methods that accept a callback, return a Promise when the callback is not specified if Promise support is available.

The Promise implementation can be customized using the bcrypt.promises.use() method:

javascript
// Example: Using a custom Promise implementation
const bluebird = require('bluebird');
bcrypt.promises.use(bluebird);
text
javascript
bcrypt.hash(myPlaintextPassword, saltRounds).then(function(hash) {
// Store hash in your password DB.
});
text
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
});
text
This is also compatible with 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
}

//...
}

text

ESM import

javascript
import bcrypt from "bcrypt";

// later
await bcrypt.compare(password, hash);

text

sync

javascript
const bcrypt = require('bcrypt');
const saltRounds = 10;
const myPlaintextPassword = 's0/\/\P4$$w0rD';
const someOtherPlaintextPassword = 'not_bacon';
text
#### To hash a password:

Technique 1 (generate a salt and hash on separate function calls):

javascript
const salt = bcrypt.genSaltSync(saltRounds);
const hash = bcrypt.hashSync(myPlaintextPassword, salt);
// Store hash in your password DB.
text
Technique 2 (auto-gen a salt and hash):
javascript
const hash = bcrypt.hashSync(myPlaintextPassword, saltRounds);
// Store hash in your password DB.
text
As with async, both techniques achieve the same end-result.

#### To check a password:

javascript
// Load hash from your password DB.
bcrypt.compareSync(myPlaintextPassword, hash); // true
bcrypt.compareSync(someOtherPlaintextPassword, hash); // false
text
A Note on Timing Attacks


We recommend using async API if you use
bcrypt on a server. Bcrypt hashing is CPU intensive which will cause the sync APIs to block the event loop and prevent your application from servicing any inbound requests or events. The async version uses a thread pool which does not block the main event loop.

API

BCrypt.

* genSaltSync(rounds, minor)
*
rounds - [OPTIONAL] - the cost of processing the data. (default - 10)
*
minor - [OPTIONAL] - minor version of bcrypt to use. (default - b)
*
genSalt(rounds, minor, cb)
*
rounds - [OPTIONAL] - the cost of processing the data. (default - 10)
*
minor - [OPTIONAL] - minor version of bcrypt to use. (default - b)
*
cb - [OPTIONAL] - a callback to be fired once the salt has been generated. If cb is not specified, a Promise is returned if Promise support is available.
*
err - First parameter to the callback detailing any errors.
*
salt - Second parameter to the callback providing the generated salt.
*
hashSync(data, salt)
*
data - [REQUIRED] - the data to be encrypted (string or Buffer).
*
salt - [REQUIRED] - the salt to be used to hash the password. If specified as a number then a salt will be generated with the specified number of rounds and used (see example under Usage).
*
hash(data, salt, cb)
*
data - [REQUIRED] - the data to be encrypted (string or Buffer).
*
salt - [REQUIRED] - the salt to be used to hash the password. If specified as a number then a salt will be generated with the specified number of rounds and used (see example under Usage).
*
cb - [OPTIONAL] - a callback to be fired once the data has been encrypted. If cb is not specified, a Promise is returned if Promise support is available.
*
err - First parameter to the callback detailing any errors.
*
encrypted - Second parameter to the callback providing the encrypted form.
*
compareSync(data, encrypted)
*
data - [REQUIRED] - data to compare (string or Buffer).
*
encrypted - [REQUIRED] - data to be compared to.
*
compare(data, encrypted, cb)
*
data - [REQUIRED] - data to compare (string or Buffer).
*
encrypted - [REQUIRED] - data to be compared to.
*
cb - [OPTIONAL] - a callback to be fired once the data has been compared. If cb is not specified, a Promise is returned if Promise support is available.
*
err - First parameter to the callback detailing any errors.
*
same - Second parameter to the callback providing whether the data and encrypted forms match [true | false].
*
getRounds(encrypted) - return the number of rounds used to encrypt a given hash
*
encrypted - [REQUIRED] - hash from which the number of rounds used should be extracted.
*
promises.use(promiseImplementation) - change the Promise implementation that bcrypt uses
*
promiseImplementation - [REQUIRED] - a Promises/A+ compatible implementation to be used.

A Note on Rounds

A note about the cost: when you are hashing your data, the module will go through a series of rounds to give you a secure hash. The value you submit is not just the number of rounds the module will go through to hash your data. The module will use the value you enter and go through 2^rounds hashing iterations.

From @garthk, on a 2GHz core you can roughly expect:

rounds=8 : ~40 hashes/sec
rounds=9 : ~20 hashes/sec
rounds=10: ~10 hashes/sec
rounds=11: ~5 hashes/sec
rounds=12: 2-3 hashes/sec
rounds=13: ~1 sec/hash
rounds=14: ~1.5 sec/hash
rounds=15: ~3 sec/hash
rounds=25: ~1 hour/hash
rounds=31: 2-3 days/hash


A Note on Timing Attacks

Because it's come up multiple times in this project and other bcrypt projects, it needs to be said. The bcrypt library is not susceptible to timing attacks. From codahale/bcrypt-ruby#42:

One of the desired properties of a cryptographic hash function is preimage attack resistance, which means there is no shortcut for generating a message which, when hashed, produces a specific digest.

A great thread on this, in much more detail can be found @ codahale/bcrypt-ruby#43

If you're unfamiliar with timing attacks and want to learn more you can find a great writeup @ [A Lesson In Timing Attacks][timingatk]

However, the comparison function is _not_ time safe (constant-time), as it may exit early when a mismatch is found. Normally, this could enable a timing attack, but because it compares full bcrypt hash digests rather than raw passwords, and hashes are preimage-resistant, an attacker cannot gain any information about the stored hash. If you use the comparison function outside the bcrypt library, we cannot guarantee its security. Keep this in mind when using the library.

Hash Info

The characters that comprise the resultant hash are ./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789$.

Resultant hashes will be 60 characters long and they will include the salt among other parameters, as follows:

$[algorithm]$[cost]$[salt][hash]

- 2 chars hash algorithm identifier prefix. "$2a$" or "$2b$" indicates BCrypt
- Cost-factor (n). Represents the exponent used to determine how many iterations 2^n
- 16-byte (128-bit) salt, base64 encoded to 22 characters
- 24-byte (192-bit) hash, base64 encoded to 31 characters

Example:


$2b$10$nOUIs5kJ7naTuTFkBy1veuK0kSxUFXfuaOKdOKf9xYT0KKIGSJwFa
| | | |
| | | hash-value = K0kSxUFXfuaOKdOKf9xYT0KKIGSJwFa
| | |
| | salt = nOUIs5kJ7naTuTFkBy1veu
| |
| cost-factor => 10 = 2^10 rounds
|
hash-algorithm identifier => 2b = BCrypt
text

Testing

If you create a pull request, tests better pass :)


npm install
npm test
`

Credits

The code for this comes from a few sources:

* blowfish.cc - OpenBSD
* bcrypt.cc - OpenBSD
* bcrypt::gen_salt - [gen_salt inclusion to bcrypt][bcryptgs]
* bcrypt_node.cc - me

Contributors

* [Antonio Salazar Cardozo][shadowfiend] - Early MacOS X support (when we used libbsd)
* [Ben Glow][pixelglow] - Fixes for thread safety with async calls
* [Van Nguyen][thegoleffect] - Found a timing attack in the comparator
* [NewITFarmer][newitfarmer] - Initial Cygwin support
* [David Trejo][dtrejo] - packaging fixes
* [Alfred Westerveld][alfredwesterveld] - packaging fixes
* [Vincent Cรดtรฉ-Roy][vincentr] - Testing around concurrency issues
* [Lloyd Hilaiel][lloyd] - Documentation fixes
* [Roman Shtylman][shtylman] - Code refactoring, general rot reduction, compile options, better memory management with delete and new, and an upgrade to libuv over eio/ev.
* [Vadim Graboys][vadimg] - Code changes to support 0.5.5+
* [Ben Noordhuis][bnoordhuis] - Fixed a thread safety issue in nodejs that was perfectly mappable to this module.
* [Nate Rajlich][tootallnate] - Bindings and build process.
* [Sean McArthur][seanmonstar] - Windows Support
* [Fanie Oosthuysen][weareu] - Windows Support
* [Amitosh Swain Mahapatra][recrsn] - $2b$ hash support, ES6 Promise support
* [Nicola Del Gobbo][NickNaso] - Initial implementation with N-API

License


Unless stated elsewhere, file headers or otherwise, the license as stated in the LICENSE file.

[bcryptwiki]: https://en.wikipedia.org/wiki/Bcrypt
[bcryptgs]: http://mail-index.netbsd.org/tech-crypto/2002/05/24/msg000204.html
[codahale]: http://codahale.com/how-to-safely-store-a-password/
[gh13]: https://github.com/ncb000gt/node.bcrypt.js/issues/13
[jtr]: http://www.openwall.com/lists/oss-security/2011/06/20/2
[depsinstall]: https://github.com/kelektiv/node.bcrypt.js/wiki/Installation-Instructions
[timingatk]: https://web.archive.org/web/20250815071532/https://codahale.com/a-lesson-in-timing-attacks/
[wrap-around-bug]: https://github.com/kelektiv/node.bcrypt.js/wiki/Security-Issues-and-Concerns#bcrypt-wrap-around-bug-medium-severity
[improper-nuls]: https://github.com/kelektiv/node.bcrypt.js/wiki/Security-Issues-and-Concerns#improper-nul-handling-medium-severity

[shadowfiend]:https://github.com/Shadowfiend
[thegoleffect]:https://github.com/thegoleffect
[pixelglow]:https://github.com/pixelglow
[dtrejo]:https://github.com/dtrejo
[alfredwesterveld]:https://github.com/alfredwesterveld
[newitfarmer]:https://github.com/newitfarmer
[zooko]:https://twitter.com/zooko
[vincentr]:https://twitter.com/vincentcr
[lloyd]:https://github.com/lloyd
[shtylman]:https://github.com/shtylman
[vadimg]:https://github.com/vadimg
[bnoordhuis]:https://github.com/bnoordhuis
[tootallnate]:https://github.com/tootallnate
[seanmonstar]:https://github.com/seanmonstar
[weareu]:https://github.com/weareu
[recrsn]:https://github.com/recrsn
[NickNaso]: https://github.com/NickNaso

---

SECURITY

Security Policy

As with any software, bcrypt` is likely to have bugs. Please report any security vulnerabilities responsibly

Supported Versions

| Version | Supported |
| ------- | ------------------ |
| 5.0.x | :white_check_mark: |
| < 5.0 | :x: |

Reporting a Vulnerability

If you are reporting a security vulnerability, please refrain from opening a GitHub issue and instead mail it to
one of the maintainers listed in the README.

---