Skip to content
This repository has been archived by the owner on Apr 3, 2019. It is now read-only.

Commit

Permalink
refactor(crypto): fall back to node's scrypt implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
philbooth committed Feb 1, 2019
1 parent c503e67 commit 6d945c8
Show file tree
Hide file tree
Showing 3 changed files with 71 additions and 36 deletions.
37 changes: 32 additions & 5 deletions lib/crypto/scrypt.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,21 @@

'use strict'

var P = require('../promise')
var scrypt_hash = require('scrypt-hash')
const crypto = require('crypto')
const P = require('../promise')

// Magic numbers from the node crypto docs:
// https://nodejs.org/api/crypto.html#crypto_crypto_scrypt_password_salt_keylen_options_callback
const DEFAULT_N = 16384
const DEFAULT_R = 8
const MAXMEM_MULTIPLIER = 256
const DEFAULT_MAXMEM = MAXMEM_MULTIPLIER * DEFAULT_N * DEFAULT_R

let scryptHash
try {
scryptHash = require('scrypt-hash')
} catch (err) {
}

// The maximum numer of hash operations allowed concurrently.
// This can be customized by setting the `maxPending` attribute on the
Expand Down Expand Up @@ -43,12 +56,26 @@ module.exports = function(log, config) {
if (scrypt.numPending > scrypt.numPendingHWM) {
scrypt.numPendingHWM = scrypt.numPending
}
scrypt_hash(input, salt, N, r, p, len,
function (err, hash) {
if (scryptHash) {
scryptHash(input, salt, N, r, p, len, (err, hash) => {
scrypt.numPending -= 1
return err ? d.reject(err) : d.resolve(hash.toString('hex'))
})
} else if (crypto.scrypt) {
let maxmem = DEFAULT_MAXMEM
if (N > DEFAULT_N || r > DEFAULT_R) {
// Conservatively prevent `memory limit exceeded` errors. See the docs for more info:
// https://nodejs.org/api/crypto.html#crypto_crypto_scrypt_password_salt_keylen_options_callback
maxmem = MAXMEM_MULTIPLIER * (N || DEFAULT_N) * (r || DEFAULT_R)
}
)
crypto.scrypt(input, salt, len, { N, r, p, maxmem }, (err, hash) => {
scrypt.numPending -= 1
return err ? d.reject(err) : d.resolve(hash.toString('hex'))
})
} else {
scrypt.numPending -= 1
d.reject(new Error('missing scrypt implementation'))
}
}
return d.promise
}
Expand Down
66 changes: 36 additions & 30 deletions npm-shrinkwrap.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -88,12 +88,14 @@
"safe-regex": "1.1.0",
"safe-url-assembler": "1.3.5",
"sandbox": "0.8.6",
"scrypt-hash": "1.1.14",
"through": "2.3.8",
"urijs": "1.19.1",
"uuid": "1.4.1",
"web-push": "3.3.0"
},
"optionalDependencies": {
"scrypt-hash": "1.1.14"
},
"devDependencies": {
"acorn": "^5.7.3",
"audit-filter": "0.3.0",
Expand Down

0 comments on commit 6d945c8

Please sign in to comment.