如何在Node.js中生成一个随机的32字节缓冲区?

6
我试图创建一个随机的32字节缓冲区,以下是我的代码(尚未起作用):
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)

有人知道一个好的方法来做这件事吗?


4
value的值不为一个16位无符号整数时,行为是未定义的。你正在传递一个字符串作为value参数。 - jonrsharpe
2个回答

13
您可以使用crypto.randomBytes函数:
import { randomBytes } from 'crypto'
const buf = randomBytes(32)
console.log('Random Buffer: ', buf)

如果您有一个 CommonJS 文件而不是模块,您需要使用 const { randomBytes } = require('crypto') 而不是第一行代码。


1
谢谢,我发现我需要 let crypto = require('crypto') - Lee

4

您可以使用crypto.randomFill来填充缓冲区:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接