/ node_modules / bcrypt / README.md
README.md
  1  # node.bcrypt.js
  2  
  3  [![ci](https://github.com/kelektiv/node.bcrypt.js/actions/workflows/ci.yaml/badge.svg)](https://github.com/kelektiv/node.bcrypt.js/actions/workflows/ci.yaml)
  4  
  5  [![Build Status](https://ci.appveyor.com/api/projects/status/github/kelektiv/node.bcrypt.js)](https://ci.appveyor.com/project/defunctzombie/node-bcrypt-js-pgo26/branch/master)
  6  
  7  A library to help you hash passwords.
  8  
  9  You can read about [bcrypt in Wikipedia][bcryptwiki] as well as in the following article:
 10  [How To Safely Store A Password][codahale]
 11  
 12  ## If You Are Submitting Bugs or Issues
 13  
 14  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.
 15  
 16  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.
 17  
 18  
 19  ## Version Compatibility
 20  
 21  _Please upgrade to atleast v5.0.0 to avoid security issues mentioned below._
 22  
 23  | Node Version   |   Bcrypt Version  |
 24  | -------------- | ------------------|
 25  | 0.4            | <= 0.4            |
 26  | 0.6, 0.8, 0.10 | >= 0.5            |
 27  | 0.11           | >= 0.8            |
 28  | 4              | <= 2.1.0          |
 29  | 8              | >= 1.0.3 < 4.0.0  |
 30  | 10, 11         | >= 3              |
 31  | 12 onwards     | >= 3.0.6          |
 32  
 33  `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:
 34  
 35  ```
 36  gyp ERR! stack Error: "pre" versions of node cannot be installed, use the --nodedir flag instead
 37  ```
 38  
 39  ## Security Issues And Concerns
 40  
 41  > 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.
 42  
 43  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.
 44  
 45  Here is a list of BCrypt-related security issues/concerns that have come up over the years.
 46  
 47  * 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].
 48  * 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.
 49  * 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.
 50  
 51  ## Compatibility Note
 52  
 53  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.
 54  
 55  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.
 56  
 57  ### Migrating from v1.0.x
 58  
 59  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`.
 60  
 61  Hashes generated in `v2.x.x` using the defaults parameters will not work in earlier versions.
 62  
 63  ## Dependencies
 64  
 65  * NodeJS
 66  * `node-gyp`
 67   * Please check the dependencies for this tool at: https://github.com/nodejs/node-gyp
 68    * Windows users will need the options for c# and c++ installed with their visual studio instance.
 69    * Python 2.x/3.x
 70  * `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).
 71  
 72  ## Install via NPM
 73  
 74  ```
 75  npm install bcrypt
 76  ```
 77  ***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```
 78  
 79  _Pre-built binaries for various NodeJS versions are made available on a best-effort basis._
 80  
 81  Only the current stable and supported LTS releases are actively tested against.
 82  
 83  _There may be an interval between the release of the module and the availabilty of the compiled modules._
 84  
 85  Currently, we have pre-built binaries that support the following platforms:
 86  
 87  1. Windows x32 and x64
 88  2. Linux x64 (GlibC and musl)
 89  3. macOS
 90  
 91  If you face an error like this:
 92  
 93  ```
 94  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
 95  ```
 96  
 97  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].
 98  
 99  ## Usage
100  
101  ### async (recommended)
102  
103  ```javascript
104  const bcrypt = require('bcrypt');
105  const saltRounds = 10;
106  const myPlaintextPassword = 's0/\/\P4$$w0rD';
107  const someOtherPlaintextPassword = 'not_bacon';
108  ```
109  
110  #### To hash a password:
111  
112  Technique 1 (generate a salt and hash on separate function calls):
113  
114  ```javascript
115  bcrypt.genSalt(saltRounds, function(err, salt) {
116      bcrypt.hash(myPlaintextPassword, salt, function(err, hash) {
117          // Store hash in your password DB.
118      });
119  });
120  ```
121  
122  Technique 2 (auto-gen a salt and hash):
123  
124  ```javascript
125  bcrypt.hash(myPlaintextPassword, saltRounds, function(err, hash) {
126      // Store hash in your password DB.
127  });
128  ```
129  
130  Note that both techniques achieve the same end-result.
131  
132  #### To check a password:
133  
134  ```javascript
135  // Load hash from your password DB.
136  bcrypt.compare(myPlaintextPassword, hash, function(err, result) {
137      // result == true
138  });
139  bcrypt.compare(someOtherPlaintextPassword, hash, function(err, result) {
140      // result == false
141  });
142  ```
143  
144  [A Note on Timing Attacks](#a-note-on-timing-attacks)
145  
146  ### with promises
147  
148  bcrypt uses whatever `Promise` implementation is available in `global.Promise`. NodeJS >= 0.12 has a native `Promise` implementation built in. However, this should work in any Promises/A+ compliant implementation.
149  
150  Async methods that accept a callback, return a `Promise` when callback is not specified if Promise support is available.
151  
152  ```javascript
153  bcrypt.hash(myPlaintextPassword, saltRounds).then(function(hash) {
154      // Store hash in your password DB.
155  });
156  ```
157  ```javascript
158  // Load hash from your password DB.
159  bcrypt.compare(myPlaintextPassword, hash).then(function(result) {
160      // result == true
161  });
162  bcrypt.compare(someOtherPlaintextPassword, hash).then(function(result) {
163      // result == false
164  });
165  ```
166  
167  This is also compatible with `async/await`
168  
169  ```javascript
170  async function checkUser(username, password) {
171      //... fetch user from a db etc.
172  
173      const match = await bcrypt.compare(password, user.passwordHash);
174  
175      if(match) {
176          //login
177      }
178  
179      //...
180  }
181  ```
182  
183  ### ESM import
184  ```javascript
185  import bcrypt from "bcrypt";
186  
187  // later
188  await bcrypt.compare(password, hash);
189  ```
190  
191  ### sync
192  
193  ```javascript
194  const bcrypt = require('bcrypt');
195  const saltRounds = 10;
196  const myPlaintextPassword = 's0/\/\P4$$w0rD';
197  const someOtherPlaintextPassword = 'not_bacon';
198  ```
199  
200  #### To hash a password:
201  
202  Technique 1 (generate a salt and hash on separate function calls):
203  
204  ```javascript
205  const salt = bcrypt.genSaltSync(saltRounds);
206  const hash = bcrypt.hashSync(myPlaintextPassword, salt);
207  // Store hash in your password DB.
208  ```
209  
210  Technique 2 (auto-gen a salt and hash):
211  
212  ```javascript
213  const hash = bcrypt.hashSync(myPlaintextPassword, saltRounds);
214  // Store hash in your password DB.
215  ```
216  
217  As with async, both techniques achieve the same end-result.
218  
219  #### To check a password:
220  
221  ```javascript
222  // Load hash from your password DB.
223  bcrypt.compareSync(myPlaintextPassword, hash); // true
224  bcrypt.compareSync(someOtherPlaintextPassword, hash); // false
225  ```
226  
227  [A Note on Timing Attacks](#a-note-on-timing-attacks)
228  
229  ### Why is async mode recommended over sync mode?
230  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.
231  
232  ## API
233  
234  `BCrypt.`
235  
236    * `genSaltSync(rounds, minor)`
237      * `rounds` - [OPTIONAL] - the cost of processing the data. (default - 10)
238      * `minor` - [OPTIONAL] - minor version of bcrypt to use. (default - b)
239    * `genSalt(rounds, minor, cb)`
240      * `rounds` - [OPTIONAL] - the cost of processing the data. (default - 10)
241      * `minor` - [OPTIONAL] - minor version of bcrypt to use. (default - b)
242      * `cb` - [OPTIONAL] - a callback to be fired once the salt has been generated. uses eio making it asynchronous. If `cb` is not specified, a `Promise` is returned if Promise support is available.
243        * `err` - First parameter to the callback detailing any errors.
244        * `salt` - Second parameter to the callback providing the generated salt.
245    * `hashSync(data, salt)`
246      * `data` - [REQUIRED] - the data to be encrypted.
247      * `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**).
248    * `hash(data, salt, cb)`
249      * `data` - [REQUIRED] - the data to be encrypted.
250      * `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**).
251      * `cb` - [OPTIONAL] - a callback to be fired once the data has been encrypted. uses eio making it asynchronous. If `cb` is not specified, a `Promise` is returned if Promise support is available.
252        * `err` - First parameter to the callback detailing any errors.
253        * `encrypted` - Second parameter to the callback providing the encrypted form.
254    * `compareSync(data, encrypted)`
255      * `data` - [REQUIRED] - data to compare.
256      * `encrypted` - [REQUIRED] - data to be compared to.
257    * `compare(data, encrypted, cb)`
258      * `data` - [REQUIRED] - data to compare.
259      * `encrypted` - [REQUIRED] - data to be compared to.
260      * `cb` - [OPTIONAL] - a callback to be fired once the data has been compared. uses eio making it asynchronous. If `cb` is not specified, a `Promise` is returned if Promise support is available.
261        * `err` - First parameter to the callback detailing any errors.
262        * `same` - Second parameter to the callback providing whether the data and encrypted forms match [true | false].
263    * `getRounds(encrypted)` - return the number of rounds used to encrypt a given hash
264      * `encrypted` - [REQUIRED] - hash from which the number of rounds used should be extracted.
265  
266  ## A Note on Rounds
267  
268  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.
269  
270  From @garthk, on a 2GHz core you can roughly expect:
271  
272      rounds=8 : ~40 hashes/sec
273      rounds=9 : ~20 hashes/sec
274      rounds=10: ~10 hashes/sec
275      rounds=11: ~5  hashes/sec
276      rounds=12: 2-3 hashes/sec
277      rounds=13: ~1 sec/hash
278      rounds=14: ~1.5 sec/hash
279      rounds=15: ~3 sec/hash
280      rounds=25: ~1 hour/hash
281      rounds=31: 2-3 days/hash
282  
283  
284  ## A Note on Timing Attacks
285  
286  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:
287  
288  > 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.
289  
290  A great thread on this, in much more detail can be found @ codahale/bcrypt-ruby#43
291  
292  If you're unfamiliar with timing attacks and want to learn more you can find a great writeup @ [A Lesson In Timing Attacks][timingatk]
293  
294  However, timing attacks are real. And the comparison function is _not_ time safe. That means that it may exit the function early in the comparison process. Timing attacks happen because of the above. We don't need to be careful that an attacker will learn anything, and our comparison function provides a comparison of hashes. It is a utility to the overall purpose of the library. If you end up using it for something else, we cannot guarantee the security of the comparator. Keep that in mind as you use the library.
295  
296  ## Hash Info
297  
298  The characters that comprise the resultant hash are `./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789$`.
299  
300  Resultant hashes will be 60 characters long and they will include the salt among other parameters, as follows:
301  
302  `$[algorithm]$[cost]$[salt][hash]`
303  
304  - 2 chars hash algorithm identifier prefix. `"$2a$" or "$2b$"` indicates BCrypt
305  - Cost-factor (n). Represents the exponent used to determine how many iterations 2^n
306  - 16-byte (128-bit) salt, base64 encoded to 22 characters
307  - 24-byte (192-bit) hash, base64 encoded to 31 characters
308  
309  Example:
310  ```
311  $2b$10$nOUIs5kJ7naTuTFkBy1veuK0kSxUFXfuaOKdOKf9xYT0KKIGSJwFa
312   |  |  |                     |
313   |  |  |                     hash-value = K0kSxUFXfuaOKdOKf9xYT0KKIGSJwFa
314   |  |  |
315   |  |  salt = nOUIs5kJ7naTuTFkBy1veu
316   |  |
317   |  cost-factor => 10 = 2^10 rounds
318   |
319   hash-algorithm identifier => 2b = BCrypt
320  ```
321  
322  ## Testing
323  
324  If you create a pull request, tests better pass :)
325  
326  ```
327  npm install
328  npm test
329  ```
330  
331  ## Credits
332  
333  The code for this comes from a few sources:
334  
335  * blowfish.cc - OpenBSD
336  * bcrypt.cc - OpenBSD
337  * bcrypt::gen_salt - [gen_salt inclusion to bcrypt][bcryptgs]
338  * bcrypt_node.cc - me
339  
340  ## Contributors
341  
342  * [Antonio Salazar Cardozo][shadowfiend] - Early MacOS X support (when we used libbsd)
343  * [Ben Glow][pixelglow] - Fixes for thread safety with async calls
344  * [Van Nguyen][thegoleffect] - Found a timing attack in the comparator
345  * [NewITFarmer][newitfarmer] - Initial Cygwin support
346  * [David Trejo][dtrejo] - packaging fixes
347  * [Alfred Westerveld][alfredwesterveld] - packaging fixes
348  * [Vincent Côté-Roy][vincentr] - Testing around concurrency issues
349  * [Lloyd Hilaiel][lloyd] - Documentation fixes
350  * [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.
351  * [Vadim Graboys][vadimg] - Code changes to support 0.5.5+
352  * [Ben Noordhuis][bnoordhuis] - Fixed a thread safety issue in nodejs that was perfectly mappable to this module.
353  * [Nate Rajlich][tootallnate] - Bindings and build process.
354  * [Sean McArthur][seanmonstar] - Windows Support
355  * [Fanie Oosthuysen][weareu] - Windows Support
356  * [Amitosh Swain Mahapatra][recrsn] - $2b$ hash support, ES6 Promise support
357  * [Nicola Del Gobbo][NickNaso] - Initial implementation with N-API
358  
359  ## License
360  Unless stated elsewhere, file headers or otherwise, the license as stated in the LICENSE file.
361  
362  [bcryptwiki]: https://en.wikipedia.org/wiki/Bcrypt
363  [bcryptgs]: http://mail-index.netbsd.org/tech-crypto/2002/05/24/msg000204.html
364  [codahale]: http://codahale.com/how-to-safely-store-a-password/
365  [gh13]: https://github.com/ncb000gt/node.bcrypt.js/issues/13
366  [jtr]: http://www.openwall.com/lists/oss-security/2011/06/20/2
367  [depsinstall]: https://github.com/kelektiv/node.bcrypt.js/wiki/Installation-Instructions
368  [timingatk]: https://codahale.com/a-lesson-in-timing-attacks/
369  [wrap-around-bug]: https://github.com/kelektiv/node.bcrypt.js/wiki/Security-Issues-and-Concerns#bcrypt-wrap-around-bug-medium-severity
370  [improper-nuls]: https://github.com/kelektiv/node.bcrypt.js/wiki/Security-Issues-and-Concerns#improper-nul-handling-medium-severity
371  
372  [shadowfiend]:https://github.com/Shadowfiend
373  [thegoleffect]:https://github.com/thegoleffect
374  [pixelglow]:https://github.com/pixelglow
375  [dtrejo]:https://github.com/dtrejo
376  [alfredwesterveld]:https://github.com/alfredwesterveld
377  [newitfarmer]:https://github.com/newitfarmer
378  [zooko]:https://twitter.com/zooko
379  [vincentr]:https://twitter.com/vincentcr
380  [lloyd]:https://github.com/lloyd
381  [shtylman]:https://github.com/shtylman
382  [vadimg]:https://github.com/vadimg
383  [bnoordhuis]:https://github.com/bnoordhuis
384  [tootallnate]:https://github.com/tootallnate
385  [seanmonstar]:https://github.com/seanmonstar
386  [weareu]:https://github.com/weareu
387  [recrsn]:https://github.com/recrsn
388  [NickNaso]: https://github.com/NickNaso