Last active
August 10, 2020 15:32
-
-
Save ilknarf/b3ff2def3f457137c8ef524ce57f8c56 to your computer and use it in GitHub Desktop.
generate a random byte string with node's crypto.randomBytes
This file contains hidden or 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
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