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?
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?
Share Improve this question asked Jul 3, 2021 at 13:16 LeeLee 31k31 gold badges122 silver badges183 bronze badges 1 |2 Answers
Reset to default 16You 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.)
You could use crypto.randomFill
to fill the Buffer:
crypto.randomFill(buf, (err, buf) => {
console.log('Random Buffer: ', buf);
});
value
is anything other than an unsigned 16-bit integer", you're passing a string. – jonrsharpe Commented Jul 3, 2021 at 13:21