Node.js - crypto.randomBytes を使用して特定の範囲の乱数を生成する方法 質問する

Node.js - crypto.randomBytes を使用して特定の範囲の乱数を生成する方法 質問する

crypto.randomBytes を使用して特定の範囲の乱数を生成するにはどうすればよいですか?

次のような乱数を生成できるようにしたいです:

console.log(random(55, 956)); // where 55 is minimum and 956 is maximum

そして私は使用が制限されています暗号.ランダムバイト内部のみランダムこの範囲の乱数を生成する関数。

生成されたバイトを randomBytes から 16 進数または 10 進数に変換する方法はわかっていますが、ランダム バイトから特定の範囲の乱数を数学的に取得する方法がわかりません。

ベストアンサー1

特定の範囲で乱数を生成するには、次の式を使用します。

Math.random() * (high - low) + low

しかし、Math.random() の代わりに crypto.randomBytes を使用したい場合、この関数はランダムに生成されたバイトを含むバッファを返します。次に、この関数の結果をバイトから 10 進数に変換する必要があります。これは、biguint 形式パッケージを使用して実行できます。このパッケージをインストールするには、次のコマンドを使用するだけです。

npm install biguint-format --save

ここで、crypto.randomBytes の結果を 10 進数に変換する必要があります。これは次のように実行できます。

var x= crypto.randomBytes(1);
return format(x, 'dec');

これで、次のようなランダム関数を作成できます。

var crypto = require('crypto'),
    format = require('biguint-format');

function randomC (qty) {
    var x= crypto.randomBytes(qty);
    return format(x, 'dec');
}
function random (low, high) {
    return randomC(4)/Math.pow(2,4*8-1) * (high - low) + low;
}
console.log(random(50,1000));

おすすめ記事