From 75f4329e013e43af0601727e697d7455854aa028 Mon Sep 17 00:00:00 2001 From: Evan Lucas Date: Fri, 9 Dec 2016 17:13:14 -0600 Subject: [PATCH] crypto: add randomFill and randomFillSync crypto.randomFill and crypto.randomFillSync are similar to crypto.randomBytes, but allow passing in a buffer as the first argument. This allows us to reuse buffers to prevent having to create a new one on every call. PR-URL: https://github.com/nodejs/node/pull/10209 Reviewed-By: Sam Roberts Reviewed-By: James M Snell Reviewed-By: Ben Noordhuis Reviewed-By: Anna Henningsen --- doc/api/crypto.md | 62 +++++++++ lib/crypto.js | 70 ++++++++++ src/node_crypto.cc | 111 +++++++++++++-- test/parallel/test-crypto-random.js | 204 ++++++++++++++++++++++++++++ test/parallel/test-domain-crypto.js | 2 + 5 files changed, 435 insertions(+), 14 deletions(-) diff --git a/doc/api/crypto.md b/doc/api/crypto.md index 957dff9975fa52..6bf5e187b628b8 100644 --- a/doc/api/crypto.md +++ b/doc/api/crypto.md @@ -1584,6 +1584,66 @@ This should normally never take longer than a few milliseconds. The only time when generating the random bytes may conceivably block for a longer period of time is right after boot, when the whole system is still low on entropy. +### crypto.randomFillSync(buf[, offset][, size]) + + +* `buf` {Buffer|Uint8Array} Must be supplied. +* `offset` {number} Defaults to `0`. +* `size` {number} Defaults to `buf.length - offset`. + +Synchronous version of [`crypto.randomFill()`][]. + +Returns `buf` + +```js +const buf = Buffer.alloc(10); +console.log(crypto.randomFillSync(buf).toString('hex')); + +crypto.randomFillSync(buf, 5); +console.log(buf.toString('hex')); + +// The above is equivalent to the following: +crypto.randomFillSync(buf, 5, 5); +console.log(buf.toString('hex')); +``` + +### crypto.randomFill(buf[, offset][, size], callback) + + +* `buf` {Buffer|Uint8Array} Must be supplied. +* `offset` {number} Defaults to `0`. +* `size` {number} Defaults to `buf.length - offset`. +* `callback` {Function} `function(err, buf) {}`. + +This function is similar to [`crypto.randomBytes()`][] but requires the first +argument to be a [`Buffer`][] that will be filled. It also +requires that a callback is passed in. + +If the `callback` function is not provided, an error will be thrown. + +```js +const buf = Buffer.alloc(10); +crypto.randomFill(buf, (err, buf) => { + if (err) throw err; + console.log(buf.toString('hex')); +}); + +crypto.randomFill(buf, 5, (err, buf) => { + if (err) throw err; + console.log(buf.toString('hex')); +}); + +// The above is equivalent to the following: +crypto.randomFill(buf, 5, 5, (err, buf) => { + if (err) throw err; + console.log(buf.toString('hex')); +}); +``` + ### crypto.setEngine(engine[, flags])