diff --git a/README.md b/README.md new file mode 100644 index 0000000..7ea031f --- /dev/null +++ b/README.md @@ -0,0 +1,63 @@ +# random-number-csprng + +A CommonJS module for generating cryptographically secure pseudo-random numbers. + +Works in Node.js, and should work in the browser as well, using Webpack or Browserify. + +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. + +## License + +[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. + +## Donate + +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)! + +You can donate using Bitcoin, PayPal, Flattr, cash-in-mail, SEPA transfers, and pretty much anything else. + +## Contributing + +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/`. + +Build tool of choice is `gulp`; simply run `gulp` while developing, and it will watch for changes. + +Be aware that by making a pull request, you agree to release your modifications under the licenses stated above. + +## Usage + +This module will return the result asynchronously - this is necessary to avoid blocking your entire application while generating a number. + +An example: + +```javascript +var Promise = require("bluebird"); +var randomNumber = require("random-number-csprng"); + +Promise.try(function() { + return randomNumber(10, 30); +}).then(function(number) { + console.log("Your random number:", number); +}).catch({code: "RandomGenerationError"}, function(err) { + console.log("Something went wrong!"); +}); +``` + +## API + +### randomNumber(minimum, maximum, [cb]) + +Returns a Promise that resolves to a random number within the specified range. + +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`). + +* __minimum__: The lowest possible value in the range. +* __maximum__: The highest possible value in the range. Inclusive. + +Optionally also accepts a nodeback as `cb`, but seriously, you should be using [Promises](https://gist.github.com/joepie91/791640557e3e5fd80861). + +### randomNumber.RandomGenerationError + +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"`. + +The error message will provide more information, but this kind of error will generally mean that the arguments you've specified are somehow invalid. \ No newline at end of file diff --git a/gulpfile.js b/gulpfile.js new file mode 100644 index 0000000..d562f35 --- /dev/null +++ b/gulpfile.js @@ -0,0 +1,25 @@ +var gulp = require('gulp'); + +/* CoffeeScript compile deps */ +var gutil = require('gulp-util'); +var babel = require('gulp-babel'); +var cache = require('gulp-cached'); +var remember = require('gulp-remember'); +var plumber = require('gulp-plumber'); + +var source = ["src/**/*.js"] + +gulp.task('babel', function() { + return gulp.src(source) + .pipe(plumber()) + .pipe(cache("babel")) + .pipe(babel({presets: ["es2015"]}).on('error', gutil.log)).on('data', gutil.log) + .pipe(remember("babel")) + .pipe(gulp.dest("lib/")); +}); + +gulp.task('watch', function () { + gulp.watch(source, ['babel']); +}); + +gulp.task('default', ['babel', 'watch']); \ No newline at end of file diff --git a/index.js b/index.js new file mode 100644 index 0000000..507257b --- /dev/null +++ b/index.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require("./lib"); \ No newline at end of file diff --git a/lib/index.js b/lib/index.js new file mode 100644 index 0000000..e1f35e3 --- /dev/null +++ b/lib/index.js @@ -0,0 +1,122 @@ +'use strict'; + +var Promise = require("bluebird"); +var crypto = Promise.promisifyAll(require("crypto")); +var createError = require("create-error"); + +var RandomGenerationError = createError("RandomGenerationError", { + code: "RandomGenerationError" +}); + +function calculateParameters(range) { + /* This does the equivalent of: + * + * bitsNeeded = Math.ceil(Math.log2(range)); + * bytesNeeded = Math.ceil(bitsNeeded / 8); + * mask = Math.pow(2, bitsNeeded) - 1; + * + * ... however, it implements it as bitwise operations, to sidestep any + * possible implementation errors regarding floating point numbers in + * JavaScript runtimes. This is an easier solution than assessing each + * runtime and architecture individually. + */ + + var bitsNeeded = 0; + var bytesNeeded = 0; + var mask = 1; + + while (range > 0) { + if (bitsNeeded % 8 === 0) { + bytesNeeded += 1; + } + + bitsNeeded += 1; + mask = mask << 1 | 1; /* 0x00001111 -> 0x00011111 */ + range = range >> 1; /* 0x01000000 -> 0x00100000 */ + } + + return { bitsNeeded: bitsNeeded, bytesNeeded: bytesNeeded, mask: mask }; +} + +module.exports = function secureRandomNumber(minimum, maximum, cb) { + return Promise.try(function () { + if (crypto == null || crypto.randomBytesAsync == null) { + throw new RandomGenerationError("No suitable random number generator available. Ensure that your runtime is linked against OpenSSL (or an equivalent) correctly."); + } + + if (minimum == null) { + throw new RandomGenerationError("You must specify a minimum value."); + } + + if (maximum == null) { + throw new RandomGenerationError("You must specify a maximum value."); + } + + if (minimum % 1 !== 0) { + throw new RandomGenerationError("The minimum value must be an integer."); + } + + if (maximum % 1 !== 0) { + throw new RandomGenerationError("The maximum value must be an integer."); + } + + if (!(maximum > minimum)) { + throw new RandomGenerationError("The maximum value must be higher than the minimum value."); + } + + var range = maximum - minimum; + + var _calculateParameters = calculateParameters(range); + + var bitsNeeded = _calculateParameters.bitsNeeded; + var bytesNeeded = _calculateParameters.bytesNeeded; + var mask = _calculateParameters.mask; + + + if (bitsNeeded > 53) { + throw new RandomGenerationError("Cannot generate numbers larger than 53 bits."); + } + + return Promise.try(function () { + return crypto.randomBytesAsync(bytesNeeded); + }).then(function (randomBytes) { + var randomValue = 0; + + /* Turn the random bytes into an integer, using bitwise operations. */ + for (var i = 0; i < bytesNeeded; i++) { + randomValue |= randomBytes[i] << 8 * i; + } + + /* We apply the mask to reduce the amount of attempts we might need + * to make to get a number that is in range. This is somewhat like + * the commonly used 'modulo trick', but without the bias: + * + * "Let's say you invoke secure_rand(0, 60). When the other code + * generates a random integer, you might get 243. If you take + * (243 & 63)-- noting that the mask is 63-- you get 51. Since + * 51 is less than 60, we can return this without bias. If we + * got 255, then 255 & 63 is 63. 63 > 60, so we try again. + * + * The purpose of the mask is to reduce the number of random + * numbers discarded for the sake of ensuring an unbiased + * distribution. In the example above, 243 would discard, but + * (243 & 63) is in the range of 0 and 60." + * + * (Source: Scott Arciszewski) + */ + randomValue = randomValue & mask; + + if (randomValue <= range) { + /* We've been working with 0 as a starting point, so we need to + * add the `minimum` here. */ + return minimum + randomValue; + } else { + /* Outside of the acceptable range, throw it away and try again. + * We don't try any modulo tricks, as this would introduce bias. */ + return secureRandomNumber(minimum, maximum); + } + }); + }).nodeify(cb); +}; + +module.exports.RandomGenerationError = RandomGenerationError; \ No newline at end of file diff --git a/lib/random-bytes.js b/lib/random-bytes.js new file mode 100644 index 0000000..9a390c3 --- /dev/null +++ b/lib/random-bytes.js @@ -0,0 +1 @@ +"use strict"; \ No newline at end of file diff --git a/package.json b/package.json new file mode 100644 index 0000000..e546098 --- /dev/null +++ b/package.json @@ -0,0 +1,34 @@ +{ + "name": "random-number-csprng", + "version": "1.0.0", + "description": "A cryptographically secure generator for random numbers in a range.", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "repository": { + "type": "git", + "url": "git://github.com/joepie91/node-random-number-csprng" + }, + "keywords": [ + "csprng", + "random", + "number", + "crypto" + ], + "author": "Sven Slootweg", + "license": "WTFPL", + "dependencies": { + "bluebird": "^3.3.3", + "create-error": "^0.3.1" + }, + "devDependencies": { + "babel-preset-es2015": "^6.6.0", + "gulp": "^3.9.1", + "gulp-babel": "^6.1.2", + "gulp-cached": "^1.1.0", + "gulp-plumber": "^1.1.0", + "gulp-remember": "^0.3.0", + "gulp-util": "^3.0.7" + } +} diff --git a/src/index.js b/src/index.js new file mode 100644 index 0000000..a9fb872 --- /dev/null +++ b/src/index.js @@ -0,0 +1,116 @@ +'use strict'; + +const Promise = require("bluebird"); +const crypto = Promise.promisifyAll(require("crypto")); +const createError = require("create-error"); + +const RandomGenerationError = createError("RandomGenerationError", { + code: "RandomGenerationError" +}); + +function calculateParameters(range) { + /* This does the equivalent of: + * + * bitsNeeded = Math.ceil(Math.log2(range)); + * bytesNeeded = Math.ceil(bitsNeeded / 8); + * mask = Math.pow(2, bitsNeeded) - 1; + * + * ... however, it implements it as bitwise operations, to sidestep any + * possible implementation errors regarding floating point numbers in + * JavaScript runtimes. This is an easier solution than assessing each + * runtime and architecture individually. + */ + + let bitsNeeded = 0; + let bytesNeeded = 0; + let mask = 1; + + while (range > 0) { + if (bitsNeeded % 8 === 0) { + bytesNeeded += 1; + } + + bitsNeeded += 1; + mask = mask << 1 | 1; /* 0x00001111 -> 0x00011111 */ + range = range >> 1; /* 0x01000000 -> 0x00100000 */ + } + + return {bitsNeeded, bytesNeeded, mask}; +} + +module.exports = function secureRandomNumber(minimum, maximum, cb) { + return Promise.try(() => { + if (crypto == null || crypto.randomBytesAsync == null) { + throw new RandomGenerationError("No suitable random number generator available. Ensure that your runtime is linked against OpenSSL (or an equivalent) correctly."); + } + + if (minimum == null) { + throw new RandomGenerationError("You must specify a minimum value."); + } + + if (maximum == null) { + throw new RandomGenerationError("You must specify a maximum value."); + } + + if (minimum % 1 !== 0) { + throw new RandomGenerationError("The minimum value must be an integer."); + } + + if (maximum % 1 !== 0) { + throw new RandomGenerationError("The maximum value must be an integer."); + } + + if (!(maximum > minimum)) { + throw new RandomGenerationError("The maximum value must be higher than the minimum value.") + } + + let range = maximum - minimum; + let {bitsNeeded, bytesNeeded, mask} = calculateParameters(range); + + if (bitsNeeded > 53) { + throw new RandomGenerationError("Cannot generate numbers larger than 53 bits."); + } + + return Promise.try(() => { + return crypto.randomBytesAsync(bytesNeeded); + }).then((randomBytes) => { + var randomValue = 0; + + /* Turn the random bytes into an integer, using bitwise operations. */ + for (let i = 0; i < bytesNeeded; i++) { + randomValue |= (randomBytes[i] << (8 * i)); + } + + /* We apply the mask to reduce the amount of attempts we might need + * to make to get a number that is in range. This is somewhat like + * the commonly used 'modulo trick', but without the bias: + * + * "Let's say you invoke secure_rand(0, 60). When the other code + * generates a random integer, you might get 243. If you take + * (243 & 63)-- noting that the mask is 63-- you get 51. Since + * 51 is less than 60, we can return this without bias. If we + * got 255, then 255 & 63 is 63. 63 > 60, so we try again. + * + * The purpose of the mask is to reduce the number of random + * numbers discarded for the sake of ensuring an unbiased + * distribution. In the example above, 243 would discard, but + * (243 & 63) is in the range of 0 and 60." + * + * (Source: Scott Arciszewski) + */ + randomValue = randomValue & mask; + + if (randomValue <= range) { + /* We've been working with 0 as a starting point, so we need to + * add the `minimum` here. */ + return minimum + randomValue; + } else { + /* Outside of the acceptable range, throw it away and try again. + * We don't try any modulo tricks, as this would introduce bias. */ + return secureRandomNumber(minimum, maximum); + } + }); + }).nodeify(cb); +} + +module.exports.RandomGenerationError = RandomGenerationError; \ No newline at end of file diff --git a/test-distribution.js b/test-distribution.js new file mode 100644 index 0000000..9b4ed25 --- /dev/null +++ b/test-distribution.js @@ -0,0 +1,15 @@ +const randomNumber = require("./"); +const Promise = require("bluebird"); + +Promise.map((new Array(2000000)), () => { + return randomNumber(10, 30); +}).reduce((stats, number) => { + if (stats[number] == null) { + stats[number] = 0; + } + + stats[number] += 1; + return stats; +}, {}).then((stats) => { + console.log(stats); +}); \ No newline at end of file