Skip to content

Commit a7f7ef4

Browse files
committed
Initial release
1 parent 001c6bc commit a7f7ef4

File tree

8 files changed

+379
-0
lines changed

8 files changed

+379
-0
lines changed

README.md

+63
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
# random-number-csprng
2+
3+
A CommonJS module for generating cryptographically secure pseudo-random numbers.
4+
5+
Works in Node.js, and should work in the browser as well, using Webpack or Browserify.
6+
7+
This module is based on code [originally written](https://gist.github.com/sarciszewski/88a7ed143204d17c3e42) by [Scott Arciszewski](https://github.com/sarciszewski), released under the WTFPL / CC0 / ZAP.
8+
9+
## License
10+
11+
[WTFPL](http://www.wtfpl.net/txt/copying/) or [CC0](https://creativecommons.org/publicdomain/zero/1.0/), whichever you prefer. A donation and/or attribution are appreciated, but not required.
12+
13+
## Donate
14+
15+
My income consists largely of donations for my projects. If this module is useful to you, consider [making a donation](http://cryto.net/~joepie91/donate.html)!
16+
17+
You can donate using Bitcoin, PayPal, Flattr, cash-in-mail, SEPA transfers, and pretty much anything else.
18+
19+
## Contributing
20+
21+
Pull requests welcome. Please make sure your modifications are in line with the overall code style, and ensure that you're editing the files in `src/`, not those in `lib/`.
22+
23+
Build tool of choice is `gulp`; simply run `gulp` while developing, and it will watch for changes.
24+
25+
Be aware that by making a pull request, you agree to release your modifications under the licenses stated above.
26+
27+
## Usage
28+
29+
This module will return the result asynchronously - this is necessary to avoid blocking your entire application while generating a number.
30+
31+
An example:
32+
33+
```javascript
34+
var Promise = require("bluebird");
35+
var randomNumber = require("random-number-csprng");
36+
37+
Promise.try(function() {
38+
return randomNumber(10, 30);
39+
}).then(function(number) {
40+
console.log("Your random number:", number);
41+
}).catch({code: "RandomGenerationError"}, function(err) {
42+
console.log("Something went wrong!");
43+
});
44+
```
45+
46+
## API
47+
48+
### randomNumber(minimum, maximum, [cb])
49+
50+
Returns a Promise that resolves to a random number within the specified range.
51+
52+
Note that the range is __inclusive__, and both numbers __must be integer values__. It is not possible to securely generate a random value for floating point numbers, so if you are working with fractional numbers (eg. `1.24`), you will have to decide on a fixed 'precision' and turn them into integer values (eg. `124`).
53+
54+
* __minimum__: The lowest possible value in the range.
55+
* __maximum__: The highest possible value in the range. Inclusive.
56+
57+
Optionally also accepts a nodeback as `cb`, but seriously, you should be using [Promises](https://gist.github.com/joepie91/791640557e3e5fd80861).
58+
59+
### randomNumber.RandomGenerationError
60+
61+
Any errors that occur during the random number generation process will be of this type. The error object will also have a `code` property, set to the string `"RandomGenerationError"`.
62+
63+
The error message will provide more information, but this kind of error will generally mean that the arguments you've specified are somehow invalid.

gulpfile.js

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
var gulp = require('gulp');
2+
3+
/* CoffeeScript compile deps */
4+
var gutil = require('gulp-util');
5+
var babel = require('gulp-babel');
6+
var cache = require('gulp-cached');
7+
var remember = require('gulp-remember');
8+
var plumber = require('gulp-plumber');
9+
10+
var source = ["src/**/*.js"]
11+
12+
gulp.task('babel', function() {
13+
return gulp.src(source)
14+
.pipe(plumber())
15+
.pipe(cache("babel"))
16+
.pipe(babel({presets: ["es2015"]}).on('error', gutil.log)).on('data', gutil.log)
17+
.pipe(remember("babel"))
18+
.pipe(gulp.dest("lib/"));
19+
});
20+
21+
gulp.task('watch', function () {
22+
gulp.watch(source, ['babel']);
23+
});
24+
25+
gulp.task('default', ['babel', 'watch']);

index.js

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
'use strict';
2+
3+
module.exports = require("./lib");

lib/index.js

+122
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
'use strict';
2+
3+
var Promise = require("bluebird");
4+
var crypto = Promise.promisifyAll(require("crypto"));
5+
var createError = require("create-error");
6+
7+
var RandomGenerationError = createError("RandomGenerationError", {
8+
code: "RandomGenerationError"
9+
});
10+
11+
function calculateParameters(range) {
12+
/* This does the equivalent of:
13+
*
14+
* bitsNeeded = Math.ceil(Math.log2(range));
15+
* bytesNeeded = Math.ceil(bitsNeeded / 8);
16+
* mask = Math.pow(2, bitsNeeded) - 1;
17+
*
18+
* ... however, it implements it as bitwise operations, to sidestep any
19+
* possible implementation errors regarding floating point numbers in
20+
* JavaScript runtimes. This is an easier solution than assessing each
21+
* runtime and architecture individually.
22+
*/
23+
24+
var bitsNeeded = 0;
25+
var bytesNeeded = 0;
26+
var mask = 1;
27+
28+
while (range > 0) {
29+
if (bitsNeeded % 8 === 0) {
30+
bytesNeeded += 1;
31+
}
32+
33+
bitsNeeded += 1;
34+
mask = mask << 1 | 1; /* 0x00001111 -> 0x00011111 */
35+
range = range >> 1; /* 0x01000000 -> 0x00100000 */
36+
}
37+
38+
return { bitsNeeded: bitsNeeded, bytesNeeded: bytesNeeded, mask: mask };
39+
}
40+
41+
module.exports = function secureRandomNumber(minimum, maximum, cb) {
42+
return Promise.try(function () {
43+
if (crypto == null || crypto.randomBytesAsync == null) {
44+
throw new RandomGenerationError("No suitable random number generator available. Ensure that your runtime is linked against OpenSSL (or an equivalent) correctly.");
45+
}
46+
47+
if (minimum == null) {
48+
throw new RandomGenerationError("You must specify a minimum value.");
49+
}
50+
51+
if (maximum == null) {
52+
throw new RandomGenerationError("You must specify a maximum value.");
53+
}
54+
55+
if (minimum % 1 !== 0) {
56+
throw new RandomGenerationError("The minimum value must be an integer.");
57+
}
58+
59+
if (maximum % 1 !== 0) {
60+
throw new RandomGenerationError("The maximum value must be an integer.");
61+
}
62+
63+
if (!(maximum > minimum)) {
64+
throw new RandomGenerationError("The maximum value must be higher than the minimum value.");
65+
}
66+
67+
var range = maximum - minimum;
68+
69+
var _calculateParameters = calculateParameters(range);
70+
71+
var bitsNeeded = _calculateParameters.bitsNeeded;
72+
var bytesNeeded = _calculateParameters.bytesNeeded;
73+
var mask = _calculateParameters.mask;
74+
75+
76+
if (bitsNeeded > 53) {
77+
throw new RandomGenerationError("Cannot generate numbers larger than 53 bits.");
78+
}
79+
80+
return Promise.try(function () {
81+
return crypto.randomBytesAsync(bytesNeeded);
82+
}).then(function (randomBytes) {
83+
var randomValue = 0;
84+
85+
/* Turn the random bytes into an integer, using bitwise operations. */
86+
for (var i = 0; i < bytesNeeded; i++) {
87+
randomValue |= randomBytes[i] << 8 * i;
88+
}
89+
90+
/* We apply the mask to reduce the amount of attempts we might need
91+
* to make to get a number that is in range. This is somewhat like
92+
* the commonly used 'modulo trick', but without the bias:
93+
*
94+
* "Let's say you invoke secure_rand(0, 60). When the other code
95+
* generates a random integer, you might get 243. If you take
96+
* (243 & 63)-- noting that the mask is 63-- you get 51. Since
97+
* 51 is less than 60, we can return this without bias. If we
98+
* got 255, then 255 & 63 is 63. 63 > 60, so we try again.
99+
*
100+
* The purpose of the mask is to reduce the number of random
101+
* numbers discarded for the sake of ensuring an unbiased
102+
* distribution. In the example above, 243 would discard, but
103+
* (243 & 63) is in the range of 0 and 60."
104+
*
105+
* (Source: Scott Arciszewski)
106+
*/
107+
randomValue = randomValue & mask;
108+
109+
if (randomValue <= range) {
110+
/* We've been working with 0 as a starting point, so we need to
111+
* add the `minimum` here. */
112+
return minimum + randomValue;
113+
} else {
114+
/* Outside of the acceptable range, throw it away and try again.
115+
* We don't try any modulo tricks, as this would introduce bias. */
116+
return secureRandomNumber(minimum, maximum);
117+
}
118+
});
119+
}).nodeify(cb);
120+
};
121+
122+
module.exports.RandomGenerationError = RandomGenerationError;

lib/random-bytes.js

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
"use strict";

package.json

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
{
2+
"name": "random-number-csprng",
3+
"version": "1.0.0",
4+
"description": "A cryptographically secure generator for random numbers in a range.",
5+
"main": "index.js",
6+
"scripts": {
7+
"test": "echo \"Error: no test specified\" && exit 1"
8+
},
9+
"repository": {
10+
"type": "git",
11+
"url": "git://github.com/joepie91/node-random-number-csprng"
12+
},
13+
"keywords": [
14+
"csprng",
15+
"random",
16+
"number",
17+
"crypto"
18+
],
19+
"author": "Sven Slootweg",
20+
"license": "WTFPL",
21+
"dependencies": {
22+
"bluebird": "^3.3.3",
23+
"create-error": "^0.3.1"
24+
},
25+
"devDependencies": {
26+
"babel-preset-es2015": "^6.6.0",
27+
"gulp": "^3.9.1",
28+
"gulp-babel": "^6.1.2",
29+
"gulp-cached": "^1.1.0",
30+
"gulp-plumber": "^1.1.0",
31+
"gulp-remember": "^0.3.0",
32+
"gulp-util": "^3.0.7"
33+
}
34+
}

src/index.js

+116
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
'use strict';
2+
3+
const Promise = require("bluebird");
4+
const crypto = Promise.promisifyAll(require("crypto"));
5+
const createError = require("create-error");
6+
7+
const RandomGenerationError = createError("RandomGenerationError", {
8+
code: "RandomGenerationError"
9+
});
10+
11+
function calculateParameters(range) {
12+
/* This does the equivalent of:
13+
*
14+
* bitsNeeded = Math.ceil(Math.log2(range));
15+
* bytesNeeded = Math.ceil(bitsNeeded / 8);
16+
* mask = Math.pow(2, bitsNeeded) - 1;
17+
*
18+
* ... however, it implements it as bitwise operations, to sidestep any
19+
* possible implementation errors regarding floating point numbers in
20+
* JavaScript runtimes. This is an easier solution than assessing each
21+
* runtime and architecture individually.
22+
*/
23+
24+
let bitsNeeded = 0;
25+
let bytesNeeded = 0;
26+
let mask = 1;
27+
28+
while (range > 0) {
29+
if (bitsNeeded % 8 === 0) {
30+
bytesNeeded += 1;
31+
}
32+
33+
bitsNeeded += 1;
34+
mask = mask << 1 | 1; /* 0x00001111 -> 0x00011111 */
35+
range = range >> 1; /* 0x01000000 -> 0x00100000 */
36+
}
37+
38+
return {bitsNeeded, bytesNeeded, mask};
39+
}
40+
41+
module.exports = function secureRandomNumber(minimum, maximum, cb) {
42+
return Promise.try(() => {
43+
if (crypto == null || crypto.randomBytesAsync == null) {
44+
throw new RandomGenerationError("No suitable random number generator available. Ensure that your runtime is linked against OpenSSL (or an equivalent) correctly.");
45+
}
46+
47+
if (minimum == null) {
48+
throw new RandomGenerationError("You must specify a minimum value.");
49+
}
50+
51+
if (maximum == null) {
52+
throw new RandomGenerationError("You must specify a maximum value.");
53+
}
54+
55+
if (minimum % 1 !== 0) {
56+
throw new RandomGenerationError("The minimum value must be an integer.");
57+
}
58+
59+
if (maximum % 1 !== 0) {
60+
throw new RandomGenerationError("The maximum value must be an integer.");
61+
}
62+
63+
if (!(maximum > minimum)) {
64+
throw new RandomGenerationError("The maximum value must be higher than the minimum value.")
65+
}
66+
67+
let range = maximum - minimum;
68+
let {bitsNeeded, bytesNeeded, mask} = calculateParameters(range);
69+
70+
if (bitsNeeded > 53) {
71+
throw new RandomGenerationError("Cannot generate numbers larger than 53 bits.");
72+
}
73+
74+
return Promise.try(() => {
75+
return crypto.randomBytesAsync(bytesNeeded);
76+
}).then((randomBytes) => {
77+
var randomValue = 0;
78+
79+
/* Turn the random bytes into an integer, using bitwise operations. */
80+
for (let i = 0; i < bytesNeeded; i++) {
81+
randomValue |= (randomBytes[i] << (8 * i));
82+
}
83+
84+
/* We apply the mask to reduce the amount of attempts we might need
85+
* to make to get a number that is in range. This is somewhat like
86+
* the commonly used 'modulo trick', but without the bias:
87+
*
88+
* "Let's say you invoke secure_rand(0, 60). When the other code
89+
* generates a random integer, you might get 243. If you take
90+
* (243 & 63)-- noting that the mask is 63-- you get 51. Since
91+
* 51 is less than 60, we can return this without bias. If we
92+
* got 255, then 255 & 63 is 63. 63 > 60, so we try again.
93+
*
94+
* The purpose of the mask is to reduce the number of random
95+
* numbers discarded for the sake of ensuring an unbiased
96+
* distribution. In the example above, 243 would discard, but
97+
* (243 & 63) is in the range of 0 and 60."
98+
*
99+
* (Source: Scott Arciszewski)
100+
*/
101+
randomValue = randomValue & mask;
102+
103+
if (randomValue <= range) {
104+
/* We've been working with 0 as a starting point, so we need to
105+
* add the `minimum` here. */
106+
return minimum + randomValue;
107+
} else {
108+
/* Outside of the acceptable range, throw it away and try again.
109+
* We don't try any modulo tricks, as this would introduce bias. */
110+
return secureRandomNumber(minimum, maximum);
111+
}
112+
});
113+
}).nodeify(cb);
114+
}
115+
116+
module.exports.RandomGenerationError = RandomGenerationError;

test-distribution.js

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
const randomNumber = require("./");
2+
const Promise = require("bluebird");
3+
4+
Promise.map((new Array(2000000)), () => {
5+
return randomNumber(10, 30);
6+
}).reduce((stats, number) => {
7+
if (stats[number] == null) {
8+
stats[number] = 0;
9+
}
10+
11+
stats[number] += 1;
12+
return stats;
13+
}, {}).then((stats) => {
14+
console.log(stats);
15+
});

0 commit comments

Comments
 (0)