在节点 js javascript 中生成随机 32 字节缓冲区的好方法是什么
What is a good way to generate a random 32 byte buffer in node js javascript
我正在尝试创建一个随机的 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)
有谁知道这样做的好方法吗?
您可以使用 crypto.randomFill
来填充缓冲区:
crypto.randomFill(buf, (err, buf) => {
console.log('Random Buffer: ', buf);
});
您可以使用 crypto.randomBytes
:
import { randomBytes } from 'crypto'
const buf = randomBytes(32)
console.log('Random Buffer: ', buf)
(如果你有一个 CommonJS 文件而不是一个模块,你需要 const { randomBytes } = require('crypto')
而不是第一行。)
我正在尝试创建一个随机的 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)
有谁知道这样做的好方法吗?
您可以使用 crypto.randomFill
来填充缓冲区:
crypto.randomFill(buf, (err, buf) => {
console.log('Random Buffer: ', buf);
});
您可以使用 crypto.randomBytes
:
import { randomBytes } from 'crypto'
const buf = randomBytes(32)
console.log('Random Buffer: ', buf)
(如果你有一个 CommonJS 文件而不是一个模块,你需要 const { randomBytes } = require('crypto')
而不是第一行。)