fastbcrypt 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,343 @@
1
- # Temporary Holding Version
1
+ # fastbcrypt
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Fastbcrypt is a native-accelerated password hashing library for Node.js. The bcrypt algorithm runs in a compiled C++ addon, and the asynchronous API runs hashing and verification in a worker pool.
4
+
5
+ Fastbcrypt 1.0.0 is based on `bcrypt@6.0.0` and supports the same API and hash format. [Upstream source](https://github.com/kelektiv/node.bcrypt.js/tree/v6.0.0)
6
+
7
+ You can read about [bcrypt in Wikipedia][bcryptwiki] as well as in the following article:
8
+ [How To Safely Store A Password][codahale]
9
+
10
+ ## If You Are Submitting Bugs or Issues
11
+
12
+ 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.
13
+
14
+ 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.
15
+
16
+
17
+ ## Version Compatibility
18
+
19
+ Fastbcrypt 1.0.0 requires Node.js 18 or newer.
20
+
21
+ ## Security Issues And Concerns
22
+
23
+ > 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.
24
+
25
+ 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.
26
+
27
+ Here is a list of BCrypt-related security issues/concerns that have come up over the years.
28
+
29
+ * 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].
30
+ * Upstream `bcrypt` versions before 5.0.0 could truncate passwords of 255 characters or more. [Wrap-around bug][wrap-around-bug]
31
+ * Upstream `bcrypt` versions before 5.0.0 could truncate passwords at a NUL character. [NUL handling bug][improper-nuls]
32
+
33
+ ## Compatibility Note
34
+
35
+ 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.
36
+
37
+ 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.
38
+
39
+ ### Migrating from upstream bcrypt
40
+
41
+ Change the dependency name and module specifier in your application to `fastbcrypt`. Existing bcrypt hashes with the `$2a$` and `$2b$` prefixes can be verified with `fastbcrypt.compare()`.
42
+
43
+ ## Install via NPM
44
+
45
+ ```
46
+ npm install fastbcrypt
47
+ ```
48
+
49
+ The package includes prebuilt addons for the following platforms.
50
+
51
+ * Windows x64 and ARM64
52
+ * Linux x64, ARM64, and ARM with glibc or musl
53
+ * macOS x64 and ARM64
54
+
55
+ On other platforms, the install script uses `node-gyp` to build the addon from source. [Build requirements](https://github.com/nodejs/node-gyp#installation)
56
+
57
+ ## Usage
58
+
59
+ ### async (recommended)
60
+
61
+ ```javascript
62
+ const fastbcrypt = require('fastbcrypt');
63
+ const saltRounds = 10;
64
+ const myPlaintextPassword = 's0/\/\P4$$w0rD';
65
+ const someOtherPlaintextPassword = 'not_bacon';
66
+ ```
67
+
68
+ #### To hash a password:
69
+
70
+ Technique 1 (generate a salt and hash on separate function calls):
71
+
72
+ ```javascript
73
+ fastbcrypt.genSalt(saltRounds, function(err, salt) {
74
+ fastbcrypt.hash(myPlaintextPassword, salt, function(err, hash) {
75
+ // Store hash in your password DB.
76
+ });
77
+ });
78
+ ```
79
+
80
+ Technique 2 (auto-gen a salt and hash):
81
+
82
+ ```javascript
83
+ fastbcrypt.hash(myPlaintextPassword, saltRounds, function(err, hash) {
84
+ // Store hash in your password DB.
85
+ });
86
+ ```
87
+
88
+ Note that both techniques achieve the same end-result.
89
+
90
+ #### To check a password:
91
+
92
+ ```javascript
93
+ // Load hash from your password DB.
94
+ fastbcrypt.compare(myPlaintextPassword, hash, function(err, result) {
95
+ // result == true
96
+ });
97
+ fastbcrypt.compare(someOtherPlaintextPassword, hash, function(err, result) {
98
+ // result == false
99
+ });
100
+ ```
101
+
102
+ [A Note on Timing Attacks](#a-note-on-timing-attacks)
103
+
104
+ ### with promises
105
+
106
+ Fastbcrypt returns a `Promise` when you omit the callback on an asynchronous method.
107
+
108
+ ```javascript
109
+ fastbcrypt.hash(myPlaintextPassword, saltRounds).then(function(hash) {
110
+ // Store hash in your password DB.
111
+ });
112
+ ```
113
+ ```javascript
114
+ // Load hash from your password DB.
115
+ fastbcrypt.compare(myPlaintextPassword, hash).then(function(result) {
116
+ // result == true
117
+ });
118
+ fastbcrypt.compare(someOtherPlaintextPassword, hash).then(function(result) {
119
+ // result == false
120
+ });
121
+ ```
122
+
123
+ This is also compatible with `async/await`
124
+
125
+ ```javascript
126
+ async function checkUser(username, password) {
127
+ //... fetch user from a db etc.
128
+
129
+ const match = await fastbcrypt.compare(password, user.passwordHash);
130
+
131
+ if(match) {
132
+ //login
133
+ }
134
+
135
+ //...
136
+ }
137
+ ```
138
+
139
+ ### ESM import
140
+ ```javascript
141
+ import fastbcrypt from "fastbcrypt";
142
+
143
+ // later
144
+ await fastbcrypt.compare(password, hash);
145
+ ```
146
+
147
+ ### sync
148
+
149
+ ```javascript
150
+ const fastbcrypt = require('fastbcrypt');
151
+ const saltRounds = 10;
152
+ const myPlaintextPassword = 's0/\/\P4$$w0rD';
153
+ const someOtherPlaintextPassword = 'not_bacon';
154
+ ```
155
+
156
+ #### To hash a password:
157
+
158
+ Technique 1 (generate a salt and hash on separate function calls):
159
+
160
+ ```javascript
161
+ const salt = fastbcrypt.genSaltSync(saltRounds);
162
+ const hash = fastbcrypt.hashSync(myPlaintextPassword, salt);
163
+ // Store hash in your password DB.
164
+ ```
165
+
166
+ Technique 2 (auto-gen a salt and hash):
167
+
168
+ ```javascript
169
+ const hash = fastbcrypt.hashSync(myPlaintextPassword, saltRounds);
170
+ // Store hash in your password DB.
171
+ ```
172
+
173
+ As with async, both techniques achieve the same end-result.
174
+
175
+ #### To check a password:
176
+
177
+ ```javascript
178
+ // Load hash from your password DB.
179
+ fastbcrypt.compareSync(myPlaintextPassword, hash); // true
180
+ fastbcrypt.compareSync(someOtherPlaintextPassword, hash); // false
181
+ ```
182
+
183
+ [A Note on Timing Attacks](#a-note-on-timing-attacks)
184
+
185
+ ### Why is async mode recommended over sync mode?
186
+ Use the asynchronous API when hashing passwords in a server request handler. It runs the CPU-intensive bcrypt operation in a worker pool so the main event loop can continue processing requests.
187
+
188
+ ## API
189
+
190
+ Fastbcrypt exports the following methods.
191
+
192
+ * `genSaltSync(rounds, minor)`
193
+ * `rounds` - [OPTIONAL] - the cost of processing the data. (default - 10)
194
+ * `minor` - [OPTIONAL] - minor version of bcrypt to use. (default - b)
195
+ * `genSalt(rounds, minor, cb)`
196
+ * `rounds` - [OPTIONAL] - the cost of processing the data. (default - 10)
197
+ * `minor` - [OPTIONAL] - minor version of bcrypt to use. (default - b)
198
+ * `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.
199
+ * `err` - First parameter to the callback detailing any errors.
200
+ * `salt` - Second parameter to the callback providing the generated salt.
201
+ * `hashSync(data, salt)`
202
+ * `data` - [REQUIRED] - the data to be encrypted.
203
+ * `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**).
204
+ * `hash(data, salt, cb)`
205
+ * `data` - [REQUIRED] - the data to be encrypted.
206
+ * `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**).
207
+ * `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.
208
+ * `err` - First parameter to the callback detailing any errors.
209
+ * `encrypted` - Second parameter to the callback providing the encrypted form.
210
+ * `compareSync(data, encrypted)`
211
+ * `data` - [REQUIRED] - data to compare.
212
+ * `encrypted` - [REQUIRED] - data to be compared to.
213
+ * `compare(data, encrypted, cb)`
214
+ * `data` - [REQUIRED] - data to compare.
215
+ * `encrypted` - [REQUIRED] - data to be compared to.
216
+ * `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.
217
+ * `err` - First parameter to the callback detailing any errors.
218
+ * `same` - Second parameter to the callback providing whether the data and encrypted forms match [true | false].
219
+ * `getRounds(encrypted)` - return the number of rounds used to encrypt a given hash
220
+ * `encrypted` - [REQUIRED] - hash from which the number of rounds used should be extracted.
221
+
222
+ ## A Note on Rounds
223
+
224
+ 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.
225
+
226
+ From @garthk, on a 2GHz core you can roughly expect:
227
+
228
+ rounds=8 : ~40 hashes/sec
229
+ rounds=9 : ~20 hashes/sec
230
+ rounds=10: ~10 hashes/sec
231
+ rounds=11: ~5 hashes/sec
232
+ rounds=12: 2-3 hashes/sec
233
+ rounds=13: ~1 sec/hash
234
+ rounds=14: ~1.5 sec/hash
235
+ rounds=15: ~3 sec/hash
236
+ rounds=25: ~1 hour/hash
237
+ rounds=31: 2-3 days/hash
238
+
239
+
240
+ ## A Note on Timing Attacks
241
+
242
+ The upstream discussion covers the bcrypt algorithm's resistance to recovering passwords from a hash. [Discussion](https://github.com/codahale/bcrypt-ruby/issues/42)
243
+
244
+ > 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.
245
+
246
+ A great thread on this, in much more detail can be found @ codahale/bcrypt-ruby#43
247
+
248
+ If you're unfamiliar with timing attacks and want to learn more you can find a great writeup @ [A Lesson In Timing Attacks][timingatk]
249
+
250
+ Fastbcrypt's final hash comparison can exit early. Use a dedicated constant-time comparator for applications that compare other secret values.
251
+
252
+ ## Hash Info
253
+
254
+ The characters that comprise the resultant hash are `./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789$`.
255
+
256
+ Resultant hashes will be 60 characters long and they will include the salt among other parameters, as follows:
257
+
258
+ `$[algorithm]$[cost]$[salt][hash]`
259
+
260
+ - 2 chars hash algorithm identifier prefix. `"$2a$" or "$2b$"` indicates BCrypt
261
+ - Cost-factor (n). Represents the exponent used to determine how many iterations 2^n
262
+ - 16-byte (128-bit) salt, base64 encoded to 22 characters
263
+ - 24-byte (192-bit) hash, base64 encoded to 31 characters
264
+
265
+ Example:
266
+ ```
267
+ $2b$10$nOUIs5kJ7naTuTFkBy1veuK0kSxUFXfuaOKdOKf9xYT0KKIGSJwFa
268
+ | | | |
269
+ | | | hash-value = K0kSxUFXfuaOKdOKf9xYT0KKIGSJwFa
270
+ | | |
271
+ | | salt = nOUIs5kJ7naTuTFkBy1veu
272
+ | |
273
+ | cost-factor => 10 = 2^10 rounds
274
+ |
275
+ hash-algorithm identifier => 2b = BCrypt
276
+ ```
277
+
278
+ ## Testing
279
+
280
+ If you create a pull request, tests better pass :)
281
+
282
+ ```
283
+ npm install
284
+ npm test
285
+ ```
286
+
287
+ ## Credits
288
+
289
+ The code for this comes from a few sources:
290
+
291
+ * blowfish.cc - OpenBSD
292
+ * bcrypt.cc - OpenBSD
293
+ * bcrypt::gen_salt - [gen_salt inclusion to bcrypt][bcryptgs]
294
+ * bcrypt_node.cc - upstream node.bcrypt.js contributors
295
+
296
+ ## Contributors
297
+
298
+ * [Antonio Salazar Cardozo][shadowfiend] - Early MacOS X support (when we used libbsd)
299
+ * [Ben Glow][pixelglow] - Fixes for thread safety with async calls
300
+ * [Van Nguyen][thegoleffect] - Found a timing attack in the comparator
301
+ * [NewITFarmer][newitfarmer] - Initial Cygwin support
302
+ * [David Trejo][dtrejo] - packaging fixes
303
+ * [Alfred Westerveld][alfredwesterveld] - packaging fixes
304
+ * [Vincent Côté-Roy][vincentr] - Testing around concurrency issues
305
+ * [Lloyd Hilaiel][lloyd] - Documentation fixes
306
+ * [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.
307
+ * [Vadim Graboys][vadimg] - Code changes to support 0.5.5+
308
+ * [Ben Noordhuis][bnoordhuis] - Fixed a thread safety issue in nodejs that was perfectly mappable to this module.
309
+ * [Nate Rajlich][tootallnate] - Bindings and build process.
310
+ * [Sean McArthur][seanmonstar] - Windows Support
311
+ * [Fanie Oosthuysen][weareu] - Windows Support
312
+ * [Amitosh Swain Mahapatra][recrsn] - $2b$ hash support, ES6 Promise support
313
+ * [Nicola Del Gobbo][NickNaso] - Initial implementation with N-API
314
+
315
+ ## License
316
+ Unless stated elsewhere, file headers or otherwise, the license as stated in the LICENSE file.
317
+
318
+ [bcryptwiki]: https://en.wikipedia.org/wiki/Bcrypt
319
+ [bcryptgs]: http://mail-index.netbsd.org/tech-crypto/2002/05/24/msg000204.html
320
+ [codahale]: http://codahale.com/how-to-safely-store-a-password/
321
+ [gh13]: https://github.com/ncb000gt/node.bcrypt.js/issues/13
322
+ [jtr]: http://www.openwall.com/lists/oss-security/2011/06/20/2
323
+ [timingatk]: https://codahale.com/a-lesson-in-timing-attacks/
324
+ [wrap-around-bug]: https://github.com/kelektiv/node.bcrypt.js/wiki/Security-Issues-and-Concerns#bcrypt-wrap-around-bug-medium-severity
325
+ [improper-nuls]: https://github.com/kelektiv/node.bcrypt.js/wiki/Security-Issues-and-Concerns#improper-nul-handling-medium-severity
326
+
327
+ [shadowfiend]:https://github.com/Shadowfiend
328
+ [thegoleffect]:https://github.com/thegoleffect
329
+ [pixelglow]:https://github.com/pixelglow
330
+ [dtrejo]:https://github.com/dtrejo
331
+ [alfredwesterveld]:https://github.com/alfredwesterveld
332
+ [newitfarmer]:https://github.com/newitfarmer
333
+ [zooko]:https://twitter.com/zooko
334
+ [vincentr]:https://twitter.com/vincentcr
335
+ [lloyd]:https://github.com/lloyd
336
+ [shtylman]:https://github.com/shtylman
337
+ [vadimg]:https://github.com/vadimg
338
+ [bnoordhuis]:https://github.com/bnoordhuis
339
+ [tootallnate]:https://github.com/tootallnate
340
+ [seanmonstar]:https://github.com/seanmonstar
341
+ [weareu]:https://github.com/weareu
342
+ [recrsn]:https://github.com/recrsn
343
+ [NickNaso]: https://github.com/NickNaso
package/SECURITY.md ADDED
@@ -0,0 +1,5 @@
1
+ # Fastbcrypt security policy
2
+
3
+ Report potential vulnerabilities privately to the Fastbcrypt maintainer. Include the Fastbcrypt version, Node.js version, platform, and steps to reproduce the issue.
4
+
5
+ Fastbcrypt 1.0.0 is based on `bcrypt@6.0.0`. For issues shared with the original project, follow its disclosure policy. [Upstream security policy](https://github.com/kelektiv/node.bcrypt.js/blob/v6.0.0/SECURITY.md)
package/bcrypt.js ADDED
@@ -0,0 +1,242 @@
1
+ const path = require('path');
2
+ const bindings = require('node-gyp-build')(path.resolve(__dirname));
3
+
4
+ const crypto = require('crypto');
5
+
6
+ const promises = require('./promises');
7
+
8
+ /// generate a salt (sync)
9
+ /// @param {Number} [rounds] number of rounds (default 10)
10
+ /// @return {String} salt
11
+ function genSaltSync(rounds, minor) {
12
+ // default 10 rounds
13
+ if (!rounds) {
14
+ rounds = 10;
15
+ } else if (typeof rounds !== 'number') {
16
+ throw new Error('rounds must be a number');
17
+ }
18
+
19
+ if (!minor) {
20
+ minor = 'b';
21
+ } else if (minor !== 'b' && minor !== 'a') {
22
+ throw new Error('minor must be either "a" or "b"');
23
+ }
24
+
25
+ return bindings.gen_salt_sync(minor, rounds, crypto.randomBytes(16));
26
+ }
27
+
28
+ /// generate a salt
29
+ /// @param {Number} [rounds] number of rounds (default 10)
30
+ /// @param {Function} cb callback(err, salt)
31
+ function genSalt(rounds, minor, cb) {
32
+ let error;
33
+
34
+ // if callback is first argument, then use defaults for others
35
+ if (typeof arguments[0] === 'function') {
36
+ // have to set callback first otherwise arguments are overridden
37
+ cb = arguments[0];
38
+ rounds = 10;
39
+ minor = 'b';
40
+ // callback is second argument
41
+ } else if (typeof arguments[1] === 'function') {
42
+ // have to set callback first otherwise arguments are overridden
43
+ cb = arguments[1];
44
+ minor = 'b';
45
+ }
46
+
47
+ if (!cb) {
48
+ return promises.promise(genSalt, this, [rounds, minor]);
49
+ }
50
+
51
+ // default 10 rounds
52
+ if (!rounds) {
53
+ rounds = 10;
54
+ } else if (typeof rounds !== 'number') {
55
+ // callback error asynchronously
56
+ error = new Error('rounds must be a number');
57
+ return process.nextTick(function () {
58
+ cb(error);
59
+ });
60
+ }
61
+
62
+ if (!minor) {
63
+ minor = 'b'
64
+ } else if (minor !== 'b' && minor !== 'a') {
65
+ error = new Error('minor must be either "a" or "b"');
66
+ return process.nextTick(function () {
67
+ cb(error);
68
+ });
69
+ }
70
+
71
+ crypto.randomBytes(16, function (error, randomBytes) {
72
+ if (error) {
73
+ cb(error);
74
+ return;
75
+ }
76
+
77
+ bindings.gen_salt(minor, rounds, randomBytes, cb);
78
+ });
79
+ }
80
+
81
+ /// hash data using a salt
82
+ /// @param {String|Buffer} data the data to encrypt
83
+ /// @param {String} salt the salt to use when hashing
84
+ /// @return {String} hash
85
+ function hashSync(data, salt) {
86
+ if (data == null || salt == null) {
87
+ throw new Error('data and salt arguments required');
88
+ }
89
+
90
+ if (!(typeof data === 'string' || data instanceof Buffer) || (typeof salt !== 'string' && typeof salt !== 'number')) {
91
+ throw new Error('data must be a string or Buffer and salt must either be a salt string or a number of rounds');
92
+ }
93
+
94
+ if (typeof salt === 'number') {
95
+ salt = module.exports.genSaltSync(salt);
96
+ }
97
+
98
+ return bindings.encrypt_sync(data, salt);
99
+ }
100
+
101
+ /// hash data using a salt
102
+ /// @param {String|Buffer} data the data to encrypt
103
+ /// @param {String} salt the salt to use when hashing
104
+ /// @param {Function} cb callback(err, hash)
105
+ function hash(data, salt, cb) {
106
+ let error;
107
+
108
+ if (typeof data === 'function') {
109
+ error = new Error('data must be a string or Buffer and salt must either be a salt string or a number of rounds');
110
+ return process.nextTick(function () {
111
+ data(error);
112
+ });
113
+ }
114
+
115
+ if (typeof salt === 'function') {
116
+ error = new Error('data must be a string or Buffer and salt must either be a salt string or a number of rounds');
117
+ return process.nextTick(function () {
118
+ salt(error);
119
+ });
120
+ }
121
+
122
+ // cb exists but is not a function
123
+ // return a rejecting promise
124
+ if (cb && typeof cb !== 'function') {
125
+ return promises.reject(new Error('cb must be a function or null to return a Promise'));
126
+ }
127
+
128
+ if (!cb) {
129
+ return promises.promise(hash, this, [data, salt]);
130
+ }
131
+
132
+ if (data == null || salt == null) {
133
+ error = new Error('data and salt arguments required');
134
+ return process.nextTick(function () {
135
+ cb(error);
136
+ });
137
+ }
138
+
139
+ if (!(typeof data === 'string' || data instanceof Buffer) || (typeof salt !== 'string' && typeof salt !== 'number')) {
140
+ error = new Error('data must be a string or Buffer and salt must either be a salt string or a number of rounds');
141
+ return process.nextTick(function () {
142
+ cb(error);
143
+ });
144
+ }
145
+
146
+
147
+ if (typeof salt === 'number') {
148
+ return module.exports.genSalt(salt, function (err, salt) {
149
+ return bindings.encrypt(data, salt, cb);
150
+ });
151
+ }
152
+
153
+ return bindings.encrypt(data, salt, cb);
154
+ }
155
+
156
+ /// compare raw data to hash
157
+ /// @param {String|Buffer} data the data to hash and compare
158
+ /// @param {String} hash expected hash
159
+ /// @return {bool} true if hashed data matches hash
160
+ function compareSync(data, hash) {
161
+ if (data == null || hash == null) {
162
+ throw new Error('data and hash arguments required');
163
+ }
164
+
165
+ if (!(typeof data === 'string' || data instanceof Buffer) || typeof hash !== 'string') {
166
+ throw new Error('data must be a string or Buffer and hash must be a string');
167
+ }
168
+
169
+ return bindings.compare_sync(data, hash);
170
+ }
171
+
172
+ /// compare raw data to hash
173
+ /// @param {String|Buffer} data the data to hash and compare
174
+ /// @param {String} hash expected hash
175
+ /// @param {Function} cb callback(err, matched) - matched is true if hashed data matches hash
176
+ function compare(data, hash, cb) {
177
+ let error;
178
+
179
+ if (typeof data === 'function') {
180
+ error = new Error('data and hash arguments required');
181
+ return process.nextTick(function () {
182
+ data(error);
183
+ });
184
+ }
185
+
186
+ if (typeof hash === 'function') {
187
+ error = new Error('data and hash arguments required');
188
+ return process.nextTick(function () {
189
+ hash(error);
190
+ });
191
+ }
192
+
193
+ // cb exists but is not a function
194
+ // return a rejecting promise
195
+ if (cb && typeof cb !== 'function') {
196
+ return promises.reject(new Error('cb must be a function or null to return a Promise'));
197
+ }
198
+
199
+ if (!cb) {
200
+ return promises.promise(compare, this, [data, hash]);
201
+ }
202
+
203
+ if (data == null || hash == null) {
204
+ error = new Error('data and hash arguments required');
205
+ return process.nextTick(function () {
206
+ cb(error);
207
+ });
208
+ }
209
+
210
+ if (!(typeof data === 'string' || data instanceof Buffer) || typeof hash !== 'string') {
211
+ error = new Error('data and hash must be strings');
212
+ return process.nextTick(function () {
213
+ cb(error);
214
+ });
215
+ }
216
+
217
+ return bindings.compare(data, hash, cb);
218
+ }
219
+
220
+ /// @param {String} hash extract rounds from this hash
221
+ /// @return {Number} the number of rounds used to encrypt a given hash
222
+ function getRounds(hash) {
223
+ if (hash == null) {
224
+ throw new Error('hash argument required');
225
+ }
226
+
227
+ if (typeof hash !== 'string') {
228
+ throw new Error('hash must be a string');
229
+ }
230
+
231
+ return bindings.get_rounds(hash);
232
+ }
233
+
234
+ module.exports = {
235
+ genSaltSync,
236
+ genSalt,
237
+ hashSync,
238
+ hash,
239
+ compareSync,
240
+ compare,
241
+ getRounds,
242
+ }
package/binding.gyp ADDED
@@ -0,0 +1,49 @@
1
+ {
2
+ "variables": {
3
+ "NODE_VERSION%":"<!(node -p \"process.versions.node.split(\\\".\\\")[0]\")"
4
+ },
5
+ 'targets': [
6
+ {
7
+ 'target_name': 'bcrypt_lib',
8
+ 'sources': [
9
+ 'src/blowfish.cc',
10
+ 'src/bcrypt.cc',
11
+ 'src/bcrypt_node.cc'
12
+ ],
13
+ 'defines': [
14
+ '_GNU_SOURCE',
15
+ ],
16
+ 'cflags!': [ '-fno-exceptions' ],
17
+ 'cflags_cc!': [ '-fno-exceptions' ],
18
+ 'dependencies': [
19
+ "<!(node -p \"require('node-addon-api').targets\"):node_addon_api_except",
20
+ ],
21
+ 'conditions': [
22
+ ['OS=="win"', {
23
+ "msvs_settings": {
24
+ "VCCLCompilerTool": {
25
+ "ExceptionHandling": 1
26
+ }
27
+ },
28
+ 'defines': [
29
+ 'uint=unsigned int',
30
+ ]
31
+ }],
32
+ ['OS=="mac"', {
33
+ 'cflags+': ['-fvisibility=hidden'],
34
+ "xcode_settings": {
35
+ "CLANG_CXX_LIBRARY": "libc++",
36
+ 'GCC_ENABLE_CPP_EXCEPTIONS': 'YES',
37
+ 'GCC_SYMBOLS_PRIVATE_EXTERN': 'YES', # -fvisibility=hidden
38
+ }
39
+ }],
40
+ ['OS=="zos" and NODE_VERSION <= 16',{
41
+ 'cflags': [
42
+ '-qascii',
43
+ ],
44
+ 'defines': ["NAPI_DISABLE_CPP_EXCEPTIONS"],
45
+ }],
46
+ ],
47
+ },
48
+ ]
49
+ }
package/build-all.sh ADDED
@@ -0,0 +1,37 @@
1
+ #!/bin/bash -ue
2
+
3
+ CLEAN=${CLEAN:-""}
4
+ RUN_TESTS=${RUN_TESTS:-true}
5
+
6
+ if [ -n "$CLEAN" ]; then
7
+ rm -rf build build-tmp*
8
+ rm -rf lib/binding
9
+ rm -rf prebuilds
10
+ fi
11
+
12
+ npm i -g prebuildify@5 node-gyp@9
13
+ npm ci
14
+ #npm run build
15
+
16
+ for PLATFORM in linux/amd64 linux/arm64/v8 linux/arm/v7; do
17
+ echo -- build for $PLATFORM --
18
+ BUILDER_NAME="fastbcrypt-${PLATFORM//\/-}-builder"
19
+ docker build -t "$BUILDER_NAME" \
20
+ --build-arg RUN_TESTS="$RUN_TESTS" \
21
+ --platform "$PLATFORM" .
22
+ CONTAINER=$(docker create --platform "$PLATFORM" "$BUILDER_NAME")
23
+ docker cp "$CONTAINER:/usr/local/opt/fastbcrypt/prebuilds" .
24
+ docker rm "$CONTAINER"
25
+
26
+ echo -- build for $PLATFORM Alpine --
27
+ BUILDER_NAME="fastbcrypt-${PLATFORM//\/-}-alpine-builder"
28
+ docker build -t "$BUILDER_NAME" -f Dockerfile-alpine \
29
+ --build-arg RUN_TESTS="$RUN_TESTS" \
30
+ --platform "$PLATFORM" .
31
+ CONTAINER=$(docker create --platform "$PLATFORM" "$BUILDER_NAME")
32
+ docker cp "$CONTAINER:/usr/local/opt/fastbcrypt/prebuilds" .
33
+ docker rm "$CONTAINER"
34
+
35
+ done
36
+
37
+ ls -lF prebuilds/