-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathshash.js
48 lines (38 loc) · 1.05 KB
/
shash.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
const isBuffer = require('is-buffer')
/* eslint-disable camelcase */
const {
crypto_shorthash_KEYBYTES,
crypto_shorthash_BYTES,
crypto_shorthash,
} = require('./sodium')
/**
* Compute a 8 byte short hash for some message buffer based on
* a given secret key.
* @public
* @param {Buffer} message
* @param {Buffer} secretKey
* @return {Buffer}
* @throws TypeError
* @throws RangeError
*/
function shash(message, secretKey) {
if (false === isBuffer(message)) {
throw new TypeError('shash: Expecting message to be buffer')
}
if (false === isBuffer(secretKey)) {
throw new TypeError('shash: Expecting secret key to be buffer')
}
if (0 === message.length) {
throw new RangeError('shash: Message buffer cannot be empty.')
}
if (crypto_shorthash_KEYBYTES !== secretKey.length) {
const { length } = secretKey
throw new RangeError(`shash: Invalid secret key length: ${length}`)
}
const hash = Buffer.allocUnsafe(crypto_shorthash_BYTES)
crypto_shorthash(hash, message, secretKey)
return hash
}
module.exports = {
shash
}