Skip to content

Instantly share code, notes, and snippets.

@renier
Last active November 22, 2019 19:37
Show Gist options
  • Save renier/133ccc4e418b23f35699ced997d404e4 to your computer and use it in GitHub Desktop.
Save renier/133ccc4e418b23f35699ced997d404e4 to your computer and use it in GitHub Desktop.
Generate random number with bit length specified in Node.js
const crypto = require('crypto');
// Generates a random number of the bit length specified in base 16 format (hexadecimal).
// bitLength should be a multiple of 8.
function generateRandomNumber(bitLength) {
return crypto.randomBytes(bitLength / 8).toString('hex');
}
// > generateRandomNumber(64)
// '9c493dcad246f3c1'
// > generateRandomNumber(96)
// 'ea4d8b614615975b0ccb2f57'
// > generateRandomNumber(128)
// 'c6c910b308d528f8e5d2621312878ae6'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment