最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

node.js - What is a good way to generate a random 32 byte buffer in node js javascript - Stack Overflow

programmeradmin2浏览0评论

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
  • 4 "Behavior is undefined when value is anything other than an unsigned 16-bit integer", you're passing a string. – jonrsharpe Commented Jul 3, 2021 at 13:21
Add a comment  | 

2 Answers 2

Reset to default 16

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.)

You could use crypto.randomFill to fill the Buffer:

crypto.randomFill(buf, (err, buf) => {
    console.log('Random Buffer: ', buf);
});
发布评论

评论列表(0)

  1. 暂无评论