刘明野

更安全的获取随机数 Window.crypto.getRandomValues()

Math.random()的加密安全替换方法window.crypto.getRandomValues

获取符合密码学要求的安全的随机值
获取随机数

const buffer = new Uint8Array(1)
crypto.getRandomValues(buffer)
buffer[0] / 0xff

继续上面那个例子,获取 n个字母

let arr = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
          'U', 'V', 'W', 'X', 'Y', 'Z'
        ];
let idvalue = ''
let n = 23; //这个值可以改变的,对应的生成多少个字母,根据自己需求所改
for (let i = 0; i < n; i++) {
    const randomBuffer = new Uint32Array(1);
    window.crypto.getRandomValues(randomBuffer);
    let randomNumber = randomBuffer[0] / (0xffffffff + 1);
    idvalue += arr[Math.floor(randomNumber * 26)]
}
console.log("随机数:"+idvalue+";长度:"+idvalue.length) //随机数:THIUDGYKOLVFXAWRYKHPLMF;长度:23

故 上面也可换为公共方法,来获取一定范围的随机数

function getRandomIntInclusive(min, max) {
    const randomBuffer = new Uint32Array(1);
    window.crypto.getRandomValues(randomBuffer);
    let randomNumber = randomBuffer[0] / (0xffffffff + 1);
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(randomNumber * (max - min + 1)) + min;
}

let arr = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
          'U', 'V', 'W', 'X', 'Y', 'Z'
        ];
let idvalue = ''
let n = 23; //这个值可以改变的,对应的生成多少个字母,根据自己需求所改
for (let i = 0; i < n; i++) {
    idvalue += arr[getRandomIntInclusive(0, 25)]
}

⚠️ 参数是 typedArray 类型
类型范围如下:
Int8 - [-128 : 127]
Int16 - [-32768 : 32767]
Int32 - [-2147483648 : 2147483647]
Int64 - [-9223372036854775808 : 9223372036854775807]
UInt8 - [0 : 255]
UInt16 - [0 : 65535]
UInt32 - [0 : 4294967295]
UInt64 - [0 : 18446744073709551615]

⚠️ 可用subarray来截取,而不是substring、slice、substr

⚠️ 用到Math.round()、Math.ceil()、Math.floor()的原因是:输入的不一定都是整数

本文为作者刘明野发布,未经允许禁止转载!
857
0
0
发表留言

友情链接