Skip to content

Instantly share code, notes, and snippets.

@artisonian
Created March 14, 2014 15:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save artisonian/9549982 to your computer and use it in GitHub Desktop.
Save artisonian/9549982 to your computer and use it in GitHub Desktop.
Generate random strings with crypto.randomBytes
'use strict';
var crypto = require('crypto');
var stream = require('stream');
function radixId (radix, callback) {
crypto.randomBytes(4, function (err, buf) {
if (err) { return callback(err); }
try {
callback(null, buf.readUInt32LE(0).toString(radix));
} catch (e) {
callback(e);
}
});
}
var shortId = radixId.bind(this, 36);
shortId(function (err, hash) {
if (err) { throw err; }
console.log('shortId:\t%s', hash);
});
function bufId (n, encoding, callback) {
if (typeof encoding === 'function') {
callback = encoding;
encoding = 'hex';
}
crypto.randomBytes(n, function (err, buf) {
if (err) { return callback(err); }
callback(null, buf.toString(encoding));
});
}
bufId(8, 'base64', function (err, hash) {
if (err) { throw err; }
console.log('bufId:\t%s', hash);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment