1
0
mirror of https://github.com/S2-/securerandomstring.git synced 2025-08-02 10:20:05 +02:00
Files
securerandomstring/lib/secure-random-string.js
2015-08-27 22:48:33 +02:00

39 lines
660 B
JavaScript

var crypto = require('crypto');
function srs(options, cb) {
if (typeof(options) === 'function') {
cb = options;
options = {};
} else {
options = options || {};
}
var length = options['length'] || 32;
// async path
if (cb) {
crypto.randomBytes(length, function(err, buf) {
if (err) {
return cb(err);
}
return cb(null,_finish(buf));
});
}
// sync path
else {
return _finish(crypto.randomBytes(length));
}
function _finish (buf) {
var string = buf.toString('base64');
if (options.urlsafe) {
string = string.replace(/\//g,'_').replace(/\+/g,'-');
}
return string.substr(0, length);
}
};
module.exports = srs;