UNPKG

10.1 kBMarkdownView Raw
1bcrypt.js
2=========
3Optimized bcrypt in JavaScript with zero dependencies. Compatible to the C++ [bcrypt](https://npmjs.org/package/bcrypt)
4binding on node.js and also working in the browser.
5
6<a href="https://travis-ci.org/dcodeIO/bcrypt.js"><img alt="build static" src="https://travis-ci.org/dcodeIO/bcrypt.js.svg?branch=master" /></a> <a href="https://npmjs.org/package/bcryptjs"><img src="https://img.shields.io/npm/v/bcryptjs.svg" alt=""></a> <a href="https://npmjs.org/package/bcryptjs"><img src="https://img.shields.io/npm/dm/bcryptjs.svg" alt=""></a> <a href="https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=dcode%40dcode.io&item_name=Open%20Source%20Software%20Donation&item_number=dcodeIO%2Fbcrypt.js"><img alt="donate ❤" src="https://img.shields.io/badge/donate-❤-ff2244.svg"></a>
7
8
9Security considerations
10-----------------------
11Besides incorporating a salt to protect against rainbow table attacks, bcrypt is an adaptive function: over time, the
12iteration count can be increased to make it slower, so it remains resistant to brute-force search attacks even with
13increasing computation power. ([see](http://en.wikipedia.org/wiki/Bcrypt))
14
15While bcrypt.js is compatible to the C++ bcrypt binding, it is written in pure JavaScript and thus slower ([about 30%](https://github.com/dcodeIO/bcrypt.js/wiki/Benchmark)), effectively reducing the number of iterations that can be
16processed in an equal time span.
17
18The maximum input length is 72 bytes (note that UTF8 encoded characters use up to 4 bytes) and the length of generated
19hashes is 60 characters.
20
21Usage
22-----
23The library is compatible with CommonJS and AMD loaders and is exposed globally as `dcodeIO.bcrypt` if neither is
24available.
25
26### node.js
27
28On node.js, the inbuilt [crypto module](http://nodejs.org/api/crypto.html)'s randomBytes interface is used to obtain
29secure random numbers.
30
31`npm install bcryptjs`
32
33```js
34var bcrypt = require('bcryptjs');
35...
36```
37
38### Browser
39
40In the browser, bcrypt.js relies on [Web Crypto API](http://www.w3.org/TR/WebCryptoAPI)'s getRandomValues
41interface to obtain secure random numbers. If no cryptographically secure source of randomness is available, you may
42specify one through [bcrypt.setRandomFallback](https://github.com/dcodeIO/bcrypt.js#setrandomfallbackrandom).
43
44```js
45var bcrypt = dcodeIO.bcrypt;
46...
47```
48
49or
50
51```js
52require.config({
53 paths: { "bcrypt": "/path/to/bcrypt.js" }
54});
55require(["bcrypt"], function(bcrypt) {
56 ...
57});
58```
59
60Usage - Sync
61------------
62To hash a password:
63
64```javascript
65var bcrypt = require('bcryptjs');
66var salt = bcrypt.genSaltSync(10);
67var hash = bcrypt.hashSync("B4c0/\/", salt);
68// Store hash in your password DB.
69```
70
71To check a password:
72
73```javascript
74// Load hash from your password DB.
75bcrypt.compareSync("B4c0/\/", hash); // true
76bcrypt.compareSync("not_bacon", hash); // false
77```
78
79Auto-gen a salt and hash:
80
81```javascript
82var hash = bcrypt.hashSync('bacon', 8);
83```
84
85Usage - Async
86-------------
87To hash a password:
88
89```javascript
90var bcrypt = require('bcryptjs');
91bcrypt.genSalt(10, function(err, salt) {
92 bcrypt.hash("B4c0/\/", salt, function(err, hash) {
93 // Store hash in your password DB.
94 });
95});
96```
97
98To check a password:
99
100```javascript
101// Load hash from your password DB.
102bcrypt.compare("B4c0/\/", hash, function(err, res) {
103 // res === true
104});
105bcrypt.compare("not_bacon", hash, function(err, res) {
106 // res === false
107});
108
109// As of bcryptjs 2.4.0, compare returns a promise if callback is omitted:
110bcrypt.compare("B4c0/\/", hash).then((res) => {
111 // res === true
112});
113```
114
115Auto-gen a salt and hash:
116
117```javascript
118bcrypt.hash('bacon', 8, function(err, hash) {
119});
120```
121
122**Note:** Under the hood, asynchronisation splits a crypto operation into small chunks. After the completion of a chunk, the execution of the next chunk is placed on the back of [JS event loop queue](https://developer.mozilla.org/en/docs/Web/JavaScript/EventLoop), thus efficiently sharing the computational resources with the other operations in the queue.
123
124API
125---
126### setRandomFallback(random)
127
128Sets the pseudo random number generator to use as a fallback if neither node's `crypto` module nor the Web Crypto
129API is available. Please note: It is highly important that the PRNG used is cryptographically secure and that it is
130seeded properly!
131
132| Parameter | Type | Description
133|-----------------|-----------------|---------------
134| random | *function(number):!Array.&lt;number&gt;* | Function taking the number of bytes to generate as its sole argument, returning the corresponding array of cryptographically secure random byte values.
135| **@see** | | http://nodejs.org/api/crypto.html
136| **@see** | | http://www.w3.org/TR/WebCryptoAPI/
137
138**Hint:** You might use [isaac.js](https://github.com/rubycon/isaac.js) as a CSPRNG but you still have to make sure to
139seed it properly.
140
141### genSaltSync(rounds=, seed_length=)
142
143Synchronously generates a salt.
144
145| Parameter | Type | Description
146|-----------------|-----------------|---------------
147| rounds | *number* | Number of rounds to use, defaults to 10 if omitted
148| seed_length | *number* | Not supported.
149| **@returns** | *string* | Resulting salt
150| **@throws** | *Error* | If a random fallback is required but not set
151
152### genSalt(rounds=, seed_length=, callback)
153
154Asynchronously generates a salt.
155
156| Parameter | Type | Description
157|-----------------|-----------------|---------------
158| rounds | *number &#124; function(Error, string=)* | Number of rounds to use, defaults to 10 if omitted
159| seed_length | *number &#124; function(Error, string=)* | Not supported.
160| callback | *function(Error, string=)* | Callback receiving the error, if any, and the resulting salt
161| **@returns** | *Promise* | If `callback` has been omitted
162| **@throws** | *Error* | If `callback` is present but not a function
163
164### hashSync(s, salt=)
165
166Synchronously generates a hash for the given string.
167
168| Parameter | Type | Description
169|-----------------|-----------------|---------------
170| s | *string* | String to hash
171| salt | *number &#124; string* | Salt length to generate or salt to use, default to 10
172| **@returns** | *string* | Resulting hash
173
174### hash(s, salt, callback, progressCallback=)
175
176Asynchronously generates a hash for the given string.
177
178| Parameter | Type | Description
179|-----------------|-----------------|---------------
180| s | *string* | String to hash
181| salt | *number &#124; string* | Salt length to generate or salt to use
182| callback | *function(Error, string=)* | Callback receiving the error, if any, and the resulting hash
183| progressCallback | *function(number)* | Callback successively called with the percentage of rounds completed (0.0 - 1.0), maximally once per `MAX_EXECUTION_TIME = 100` ms.
184| **@returns** | *Promise* | If `callback` has been omitted
185| **@throws** | *Error* | If `callback` is present but not a function
186
187### compareSync(s, hash)
188
189Synchronously tests a string against a hash.
190
191| Parameter | Type | Description
192|-----------------|-----------------|---------------
193| s | *string* | String to compare
194| hash | *string* | Hash to test against
195| **@returns** | *boolean* | true if matching, otherwise false
196| **@throws** | *Error* | If an argument is illegal
197
198### compare(s, hash, callback, progressCallback=)
199
200Asynchronously compares the given data against the given hash.
201
202| Parameter | Type | Description
203|-----------------|-----------------|---------------
204| s | *string* | Data to compare
205| hash | *string* | Data to be compared to
206| callback | *function(Error, boolean)* | Callback receiving the error, if any, otherwise the result
207| progressCallback | *function(number)* | Callback successively called with the percentage of rounds completed (0.0 - 1.0), maximally once per `MAX_EXECUTION_TIME = 100` ms.
208| **@returns** | *Promise* | If `callback` has been omitted
209| **@throws** | *Error* | If `callback` is present but not a function
210
211### getRounds(hash)
212
213Gets the number of rounds used to encrypt the specified hash.
214
215| Parameter | Type | Description
216|-----------------|-----------------|---------------
217| hash | *string* | Hash to extract the used number of rounds from
218| **@returns** | *number* | Number of rounds used
219| **@throws** | *Error* | If `hash` is not a string
220
221### getSalt(hash)
222
223Gets the salt portion from a hash. Does not validate the hash.
224
225| Parameter | Type | Description
226|-----------------|-----------------|---------------
227| hash | *string* | Hash to extract the salt from
228| **@returns** | *string* | Extracted salt part
229| **@throws** | *Error* | If `hash` is not a string or otherwise invalid
230
231
232Command line
233------------
234`Usage: bcrypt <input> [salt]`
235
236If the input has spaces inside, simply surround it with quotes.
237
238Downloads
239---------
240* [Distributions](https://github.com/dcodeIO/bcrypt.js/tree/master/dist)
241* [ZIP-Archive](https://github.com/dcodeIO/bcrypt.js/archive/master.zip)
242* [Tarball](https://github.com/dcodeIO/bcrypt.js/tarball/master)
243
244Credits
245-------
246Based on work started by Shane Girish at [bcrypt-nodejs](https://github.com/shaneGirish/bcrypt-nodejs) (MIT-licensed),
247which is itself based on [javascript-bcrypt](http://code.google.com/p/javascript-bcrypt/) (New BSD-licensed).
248
249License
250-------
251New-BSD / MIT ([see](https://github.com/dcodeIO/bcrypt.js/blob/master/LICENSE))