Created
March 14, 2014 15:27
-
-
Save artisonian/9549982 to your computer and use it in GitHub Desktop.
Generate random strings with crypto.randomBytes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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