Skip to content

Commit

Permalink
initial files that get the basics down
Browse files Browse the repository at this point in the history
  • Loading branch information
my8bird committed Jan 9, 2012
0 parents commit d45b3c2
Show file tree
Hide file tree
Showing 3 changed files with 80 additions and 0 deletions.
15 changes: 15 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"name": "secure_random",
"description": "",
"author": "Nathan Landis <[email protected]>",
"version": "0.0.1",
"dependencies": {
"node-uuid": "1.3.x"
},
"devDependencies": {
"mocha": ">= 0.0.8",
"should": ">= 0.4.2"
},
"engine": "node >= 0.6.3"
}

33 changes: 33 additions & 0 deletions random.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
var Buffer = require('buffer').Buffer,
crypto = require('crypto');


function _parseArgs(arg_array) {
if (arg_array.length === 0) { throw new Error('Atleast a callback argument is required'); }
var is_range = arg_array.length > 2;

return {
cb: arg_array[arg_array.length-1],
min: is_range ? arg_array[0] : undefined,
max: is_range ? arg_array[1] : undefined
};
}

/*** Returns a random unsigned Int ***
Returns the random int returned by nodes crypto library
*/
exports.getRandomInt = function(min, max, callback) {
var args = _parseArgs(arguments);

crypto.randomBytes(8, function(err, bytes_slow_buf) {
if (err) { return cb(err); }

var unsigned_int = Buffer(bytes_slow_buf).readUInt32LE(0);

if (args.min !== undefined) {
unsigned_int = unsigned_int % Math.abs(args.max - args.min) + args.min;
}

args.cb(null, unsigned_int);
});
};
32 changes: 32 additions & 0 deletions test_random.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
var random = require('./random'),
should = require('should');


describe('Random', function(){
describe('Using Min and Max', function() {
var iteration = 3000;

it('should return a random number if no range is supplied', function(done) {
var i, j=0;
for (i=0; i < iteration; i++) {
random.getRandomInt(function(err, value) {
if (err) {throw err;}
value.should.be.a('number');
if (++j === iteration) {done();}
});
}
});

it('should return a random number greater then min', function(done){
var i, j=0;
for (i=0; i < iteration; i++) {
random.getRandomInt(20, 100, function(err, value) {
if (err) {throw err;}
value.should.be.a('number');
value.should.be.within(20, 100);
if (++j === iteration) {done();}
});
}
})
})
})

0 comments on commit d45b3c2

Please sign in to comment.