commit 20def6c1897d7b0837be13d20c13c3f5de6823a8 Author: s2 Date: Wed Apr 22 20:47:04 2015 +0200 initial commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..650751b --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +/.settings +/.project diff --git a/lib/securerandomstring.js b/lib/securerandomstring.js new file mode 100644 index 0000000..bbaa0c2 --- /dev/null +++ b/lib/securerandomstring.js @@ -0,0 +1,17 @@ +var crypto = require('crypto'); + +function securerandomstring(cb, options) { + options = options || {}; + var length = options['length'] || 32; + + crypto.randomBytes(length, function(ex, buf) { + if (ex) throw ex; + + var string = buf.toString('base64'); + cb(string.substr(0, length)); + }); + +}; + + +module.exports = securerandomstring; diff --git a/package.json b/package.json new file mode 100644 index 0000000..6ebcf5a --- /dev/null +++ b/package.json @@ -0,0 +1,24 @@ +{ + "name": "securerandomstring", + "version": "0.0.1", + "description": "Generates a secure random string with a given length", + "main": "lib/securerandomstring.js", + "scripts": { + "test": "tests.js" + }, + "repository": { + "type": "git", + "url": "https://github.com/S2-/securerandomstring.git" + }, + "keywords": [ + "secure", + "random", + "string" + ], + "author": "Simon Santoro", + "license": "ISC", + "bugs": { + "url": "https://github.com/S2-/securerandomstring/issues" + }, + "homepage": "https://github.com/S2-/securerandomstring" +} diff --git a/tests.js b/tests.js new file mode 100644 index 0000000..2ca9f81 --- /dev/null +++ b/tests.js @@ -0,0 +1,53 @@ +var securerandomstring = require('./lib/securerandomstring.js'); + + +//my awesome test framework +var test = function(name, what, ref, c) { + process.stdout.write(name); + + if (typeof(c) !== 'boolean') { + c = true; + } + + if (typeof(what) === 'function') { + what = what(); + } + if (typeof(ref) === 'function') { + ref = ref(); + } + + if ((what === ref) === c) { + process.stdout.write(' ✓'); + } else { + process.stdout.write(' ⛝\n'); + process.stdout.write(' ----> expected | ' + (typeof(ref) === 'string' ? ref.replace(/ /g, '·') + '\n' : ref + '\n')); + process.stdout.write(' ----> got | ' + (typeof(what) === 'string' ? what.replace(/ /g, '·') + '\n' : what + '\n')); + } + process.stdout.write('\n'); +}; + + + +//the actual tests +securerandomstring(function(sr) { + test('generate a random string 32 chars long', + sr.length, + 32 + ); +}); + +securerandomstring(function(sr) { + test('generate a random string 1 char long', + sr.length, + 1 + ); +}, {length: 1}); + +securerandomstring(function(sr) { + test('generate a random string 256 chars long', + sr.length, + 256 + ); +}, {length: 256}); + +