Skip to content

Instantly share code, notes, and snippets.

@ilknarf
Last active August 10, 2020 15:32
Show Gist options
  • Save ilknarf/b3ff2def3f457137c8ef524ce57f8c56 to your computer and use it in GitHub Desktop.
Save ilknarf/b3ff2def3f457137c8ef524ce57f8c56 to your computer and use it in GitHub Desktop.
generate a random byte string with node's crypto.randomBytes
const crypto = require('crypto');
let bytes = crypto.randomBytes(16);
// using bit operations (unnecessary) to get individual digits
console.log([...bytes].map(v => (v >> 4).toString(16) + (v & 15).toString(16)).join(''));
// you can directly convert the byte to hexadecimal instead, making sure to pad digits.
console.log([...bytes].map(v => v.toString(16).padStart(2, '0')).join(''));
// even better, directly convert the buffer to hex
console.log(bytes.toString('hex'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment