fcoin/lib/crypto/random.js
Christopher Jeffrey d4cc22e1c5
refactor: crypto.
2017-06-27 07:27:53 -07:00

45 lines
879 B
JavaScript

/*!
* random.js - randomness for bcoin
* Copyright (c) 2014-2017, Christopher Jeffrey (MIT License).
* https://github.com/bcoin-org/bcoin
*/
'use strict';
/**
* @module crypto.random
*/
var crypto = require('crypto');
/*
* Misc
*/
exports.randomBytes = crypto.randomBytes;
/**
* Generate a random uint32.
* Probably more cryptographically sound than
* `Math.random()`.
* @returns {Number}
*/
exports.randomInt = function randomInt() {
return exports.randomBytes(4).readUInt32LE(0, true);
};
/**
* Generate a random number within a range.
* Probably more cryptographically sound than
* `Math.random()`.
* @param {Number} min - Inclusive.
* @param {Number} max - Exclusive.
* @returns {Number}
*/
exports.randomRange = function randomRange(min, max) {
var num = exports.randomInt();
return Math.floor((num / 0x100000000) * (max - min) + min);
};