-
Notifications
You must be signed in to change notification settings - Fork 1
/
random-bytes.js
30 lines (27 loc) · 795 Bytes
/
random-bytes.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
const alloc = require('buffer-alloc-unsafe')
/* eslint-disable camelcase */
const { randombytes_buf } = require('./sodium')
/**
* Generate a sized buffer of random bytes. This function calls
* `randombytes_buf` on a buffer of specified size.
*
* @public
* @param {Number} size
* @return {Buffer}
* @throws TypeError
*/
function randomBytes(size) {
if (Number.isNaN(size)) {
throw new TypeError('crypto.randomBytes: Size cannot be NaN.')
} else if (!size || 'number' !== typeof size) {
throw new TypeError('crypto.randomBytes: Expecting size to be a number.')
} else if (size <= 0) {
throw new TypeError('crypto.randomBytes: Size must be larger than 0.')
}
const buffer = alloc(size)
randombytes_buf(buffer)
return buffer
}
module.exports = {
randomBytes
}