【问题标题】:What is a good way to generate a random 32 byte buffer in node js javascript什么是在节点 js javascript 中生成随机 32 字节缓冲区的好方法
【发布时间】:2021-07-03 13:16:34
【问题描述】:

我正在尝试创建一个随机的 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)

有谁知道这样做的好方法吗?

【问题讨论】:

标签: javascript node.js random buffer


【解决方案1】:

你可以使用crypto.randomBytes:

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

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

【讨论】:

  • 谢谢,我发现我需要let crypto = require('crypto')
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2012-12-15
    • 1970-01-01
    • 1970-01-01
    • 2018-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-02
    • 1970-01-01
    相关资源
    最近更新 更多