-
Notifications
You must be signed in to change notification settings - Fork 1
/
random-bytes.js
30 lines (26 loc) · 762 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
'use strict'
const { randombytes_buf } = require('sodium-universal')
const alloc = require('buffer-alloc-unsafe')
/**
* 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 (null == size || 'number' != typeof size) {
throw new TypeError("randomBytes: Expecting size to be a number.")
} else if (size != size) {
throw new TypeError("randomBytes: Size cannot be NaN.")
} else if (size <= 0) {
throw new TypeError("randomBytes: Size must be larger than 0.")
}
const buffer = alloc(size)
randombytes_buf(buffer)
return buffer
}
module.exports = {
randomBytes
}