生成256位随机数

por*_*ton 3 javascript random numbers bigint

我需要生成一个 256 位随机无符号数作为十进制字符串(与之前生成的任何内容发生冲突的概率几乎为零)。

如何在 JavaScript 中(在浏览器中)执行此操作?

Vis*_*ioN 7

如果您不是很受限,您可以使用新的 JavaScript 工具:

function rnd256() {
  const bytes = new Uint8Array(32);
  
  // load cryptographically random bytes into array
  window.crypto.getRandomValues(bytes);
  
  // convert byte array to hexademical representation
  const bytesHex = bytes.reduce((o, v) => o + ('00' + v.toString(16)).slice(-2), '');
  
  // convert hexademical value to a decimal string
  return BigInt('0x' + bytesHex).toString(10);
}

console.log( rnd256() );
Run Code Online (Sandbox Code Playgroud)