-
Notifications
You must be signed in to change notification settings - Fork 1
/
auth.js
81 lines (67 loc) · 1.88 KB
/
auth.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
const isBuffer = require('is-buffer')
/* eslint-disable camelcase */
const {
crypto_auth_KEYBYTES = 32,
crypto_auth_BYTES = 32,
crypto_auth_verify,
crypto_auth,
} = require('./sodium')
// export verify so we can access it like `crypto.auth.verify`
auth.verify = verify
/**
* Generates and returns a message authentication code (MAC) for
* a given message and secret key.
*
* @public
* @param {Buffer} message
* @param {Buffer} key
* @return {Buffer}
* @throws TypeError
*/
function auth(message, key) {
if (!message || false === isBuffer(message)) {
throw new TypeError('auth: Expecting message to be a buffer.')
}
if (!key || false === isBuffer(key)) {
throw new TypeError('auth: Expecting key to be a buffer.')
}
if (crypto_auth_KEYBYTES !== key.length) {
throw new TypeError(`auth: Invalid key length: ${key.length}`)
}
const out = Buffer.allocUnsafe(crypto_auth_BYTES)
crypto_auth(out, message, key)
return out
}
/**
* Verifies the authenticity of a message with a given message
* authentication code (MAC) and secret key.
*
* @public
* @param {Buffer} mac
* @param {Buffer} message
* @param {Buffer} key
* @return {Boolean}
* @throws TypeError
*/
function verify(mac, message, key) {
if (!mac || false === isBuffer(mac)) {
throw new TypeError('verify: Expecting MAC to be a buffer.')
}
if (crypto_auth_BYTES !== mac.length) {
throw new TypeError(`auth: Invalid MAC length: ${mac.length}`)
}
if (!message || false === isBuffer(message)) {
throw new TypeError('verify: Expecting message to be a buffer.')
}
if (!key || false === isBuffer(key)) {
throw new TypeError('verify: Expecting key to be a buffer.')
}
if (crypto_auth_KEYBYTES !== key.length) {
throw new TypeError(`verify: Invalid key length: ${key.length}`)
}
return Boolean(crypto_auth_verify(mac, message, key))
}
module.exports = {
verify,
auth,
}