【问题标题】:Converting random bytes to an integer range - how?将随机字节转换为整数范围 - 如何?
【发布时间】:2013-04-04 20:50:24
【问题描述】:

我试图通过从 crypto.randomBytes() 中读取来获取一个范围内的随机整数。

现在,我的问题是我不知道如何从该字节流中读取整数。我想生成一个范围只是“扔掉”不在范围内的整数的问题。

有什么想法吗?

【问题讨论】:

  • 这个问题可能会有所帮助:stackoverflow.com/questions/15753019/… 如果你能做到这一点,你可以执行 Math.floor(randomFloat() * maxInteger) 来获得 0 和 (maxInteger - 1) 之间的整数。跨度>

标签: javascript node.js


【解决方案1】:

在 NodeJS 中的[0,1) 区间(即与Math.random() 相同)中获取加密安全且均匀分布

const random = crypto.randomBytes(4).readUInt32LE() / 0x100000000;
console.log(random); //e.g. 0.9002735135145485

或在浏览器中

const random = window.crypto.getRandomValues(new Uint32Array(1))[0] / 0x100000000;
console.log(random);

【讨论】:

    【解决方案2】:
    const { randomInt } = await import('crypto');
    
    const n = randomInt(1, 7);
    console.log(`The dice rolled: ${n}`);
    

    现在在节点本身实现 https://nodejs.org/api/crypto.html#crypto_crypto_randomint_min_max_callback

    【讨论】:

    【解决方案3】:

    您可以使用以下代码从crypto.randomBytes 获取一个 32 位整数。如果您需要多个字节,可以向crypto.randomBytes 请求更多字节,然后使用substr 单独选择和转换每个整数。

    crypto.randomBytes(4, function(ex, buf) {
      var hex = buf.toString('hex');
      var myInt32 = parseInt(hex, 16);
    });
    

    话虽如此,您可能只想使用Math.floor(Math.random() * maxInteger)

    【讨论】:

    • 正是我需要的,谢谢!这是单行版本: parseInt(crypto.randomBytes(4).toString('hex'), 16);
    • 使用 crypto.randomBytes() 而不是 Math.random 的一个很好的理由是因为 cwe.mitre.org/data/definitions/330.html
    猜你喜欢
    • 2017-01-11
    • 2012-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-05
    • 1970-01-01
    • 2010-11-02
    相关资源
    最近更新 更多