Search code examples
javascriptnode.jsrandombuffer

What is a good way to generate a random 32 byte buffer in node js javascript


I'm attempting to create a random 32 byte buffer, here's what I have (not working):

let buf = Buffer.alloc(32).fill(0)
console.log('Buffer: ',buf)
buf.writeUInt16BE(Math.floor(Math.random() * 2147483647).toString(16),5)
console.log('Random Buffer: ',buf)

Does anyone know a good way to do this?


Solution

  • You can use crypto.randomBytes:

    import { randomBytes } from 'crypto'
    const buf = randomBytes(32)
    console.log('Random Buffer: ', buf)
    

    (If you have a CommonJS file and not a module, you need const { randomBytes } = require('crypto') instead of the first line.)