javascript - How to get a cryptographically strong number in the range [0,1)? - Stack Overflow

I've been trying to create a function that will return a random decimal number between 0 (inclusiv

I've been trying to create a function that will return a random decimal number between 0 (inclusive) and 1 (exclusive) via the Window.crypto.getRandomValues() function. Currently, my code is as follows:

var rand = function(){
    var ra = window.crypto.getRandomValues(new Uint32Array(1))[0];
    function dec(n,m){
        return (n>=0&&n<=1)?n:dec(n/m,m);
    }
    return dec(ra,8);
}

My problem is that this isn't uniformly distributed; it tends to be between .2 and .7, and rarely falls under .2 and over .7. Is there a better way to use the .getRandomValues() method to obtain a number like that of the Math.random() function?

I am not using the .random() method because I wish to have secure numbers for what I am trying to perform.

I've been trying to create a function that will return a random decimal number between 0 (inclusive) and 1 (exclusive) via the Window.crypto.getRandomValues() function. Currently, my code is as follows:

var rand = function(){
    var ra = window.crypto.getRandomValues(new Uint32Array(1))[0];
    function dec(n,m){
        return (n>=0&&n<=1)?n:dec(n/m,m);
    }
    return dec(ra,8);
}

My problem is that this isn't uniformly distributed; it tends to be between .2 and .7, and rarely falls under .2 and over .7. Is there a better way to use the .getRandomValues() method to obtain a number like that of the Math.random() function?

I am not using the .random() method because I wish to have secure numbers for what I am trying to perform.

Share Improve this question edited Mar 3, 2018 at 10:18 Luca Fagioli 13.4k5 gold badges64 silver badges60 bronze badges asked Nov 28, 2014 at 1:59 Conor O'BrienConor O'Brien 1,0372 gold badges17 silver badges45 bronze badges 1
  • Related question on crypto.SE. – Ilmari Karonen Commented Mar 3, 2018 at 14:06
Add a ment  | 

1 Answer 1

Reset to default 9

Why not simplify things

function cryptoRandom() {
    return window.crypto.getRandomValues(new Uint32Array(1))[0] / 0x100000000;
}

What's going on here?

  • Assume window.crypto.getRandomValues will giving us truely random bits
  • Ask for 32 bits (unsigned integer i)
  • The minium value of i is 0x00000000 (or 0)
  • The maximum value of i is 0xFFFFFFFF (or 4294967295)
  • Transform these points onto the range you want; (i - min) / (max + 1)

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745463617a4628818.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信