-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdiscovery-key.js
59 lines (51 loc) · 1.61 KB
/
discovery-key.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
const isBuffer = require('is-buffer')
const alloc = require('buffer-alloc-unsafe')
const kDefaultDiscoveryKeySize = 32
/* eslint-disable camelcase */
const {
crypto_generichash,
crypto_generichash_KEYBYTES_MIN,
} = require('./sodium')
const kDefaultDiscoveryKeyMessageKey = alloc(crypto_generichash_KEYBYTES_MIN)
kDefaultDiscoveryKeyMessageKey.fill('ara')
/**
* Generate a discovery digest useful for network
* keys. This function calls `crypto_generichash` internally.
*
* @public
* @param {Buffer|Array<Buffer>} buffer
* @param {?(Number)} [size = 32]
* @return {Buffer}
* @throws TypeError
*/
function discoveryKey(buffer, size, key) {
if (null === size || undefined === size) {
/* eslint-disable-next-line no-param-reassign */
size = kDefaultDiscoveryKeySize
} else if (Number.isNaN(size) || 'number' !== typeof size) {
/* eslint-disable-next-line function-paren-newline */
throw new TypeError(
'crypto.discoveryKey: Expecting size to be a number.'
)
} else if (size <= 0) {
/* eslint-disable-next-line function-paren-newline */
throw new TypeError(
'crypto.discoveryKey: Expecting size to be greater than 0.'
)
}
if (!key) {
/* eslint-disable-next-line no-param-reassign */
key = kDefaultDiscoveryKeyMessageKey
} else if (false === isBuffer(key)) {
throw new TypeError('crypto.discoveryKey: Expecting key to be a buffer')
}
if (false === isBuffer(buffer)) {
throw new TypeError('crypto.discoveryKey: Expecting buffer.')
}
const digest = alloc(size)
crypto_generichash(digest, buffer, key)
return digest
}
module.exports = {
discoveryKey
}