Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
80540 views
1
var compat = require('./browser')
2
var crypto = require('crypto')
3
var fork = require('child_process').fork
4
var path = require('path')
5
6
var MAX_ALLOC = Math.pow(2, 30) - 1 // default in iojs
7
8
function asyncPBKDF2 (password, salt, iterations, keylen, digest, callback) {
9
if (typeof iterations !== 'number') {
10
throw new TypeError('Iterations not a number')
11
}
12
13
if (iterations < 0) {
14
throw new TypeError('Bad iterations')
15
}
16
17
if (typeof keylen !== 'number') {
18
throw new TypeError('Key length not a number')
19
}
20
21
if (keylen < 0 || keylen > MAX_ALLOC) {
22
throw new TypeError('Bad key length')
23
}
24
25
if (typeof password === 'string') {
26
password = new Buffer(password, 'binary')
27
}
28
29
if (typeof salt === 'string') {
30
salt = new Buffer(salt, 'binary')
31
}
32
33
var child = fork(path.resolve(__dirname, 'async-shim.js'))
34
35
child.on('message', function (result) {
36
if (result.type === 'success') {
37
callback(null, new Buffer(result.data, 'hex'))
38
} else if (result.type === 'fail') {
39
callback(new TypeError(result.data))
40
}
41
})
42
43
child.send({
44
password: password.toString('hex'),
45
salt: salt.toString('hex'),
46
iterations: iterations,
47
keylen: keylen,
48
digest: digest
49
})
50
}
51
52
exports.pbkdf2Sync = function pbkdf2Sync (password, salt, iterations, keylen, digest) {
53
digest = digest || 'sha1'
54
55
if (isNode10()) {
56
if (digest === 'sha1') {
57
return crypto.pbkdf2Sync(password, salt, iterations, keylen)
58
} else {
59
return compat.pbkdf2Sync(password, salt, iterations, keylen, digest)
60
}
61
} else {
62
return crypto.pbkdf2Sync(password, salt, iterations, keylen, digest)
63
}
64
}
65
66
exports.pbkdf2 = function pbkdf2 (password, salt, iterations, keylen, digest, callback) {
67
if (typeof digest === 'function') {
68
callback = digest
69
digest = 'sha1'
70
}
71
72
if (isNode10()) {
73
if (digest === 'sha1') {
74
return crypto.pbkdf2(password, salt, iterations, keylen, callback)
75
} else {
76
return asyncPBKDF2(password, salt, iterations, keylen, digest, callback)
77
}
78
} else {
79
return crypto.pbkdf2(password, salt, iterations, keylen, digest, callback)
80
}
81
}
82
83
var sha1 = '0c60c80f961f0e71f3a9b524af6012062fe037a6e0f0eb94fe8fc46bdc637164'
84
var isNode10Result
85
86
function isNode10 () {
87
if (typeof isNode10Result === 'undefined') {
88
isNode10Result = crypto.pbkdf2Sync('password', 'salt', 1, 32, 'sha256').toString('hex') === sha1
89
}
90
91
return isNode10Result
92
}
93
94