Skip to content

getRandomValues gives 16- and 32-bit arrays only 8 random bits per element #6318

Description

@inancgumus

Brief summary

crypto.getRandomValues() never puts a value above 255 into a 16-bit or 32-bit array. A Uint32Array element should carry 32 random bits and carries 8, so anyone using one for a nonce, salt, or token gets far less randomness than they asked for. Uint8Array and Int8Array are fine.

Environment

k6 version: reproduced on v2.2.0. The same code is in v1.8.1, and it has not changed since WebCrypto landed in v0.44.0.

OS: macOS 15 (arm64), not platform specific.

Steps to reproduce the problem

export default function () {
  let max = 0;
  for (let i = 0; i < 1000; i++) {
    const a = new Uint32Array(8);
    crypto.getRandomValues(a);
    max = Math.max(max, ...a);
  }
  console.log("largest of 8000 Uint32Array values:", max);
}

Expected behaviour

A number in the billions, the way browsers and Node do it. The same loop under Node:

node largest: 4294305038

Actual behaviour

largest of 8000 Uint32Array values: 255

Uint16Array has the same ceiling. examples/webcrypto/getRandomValues.js uses a Uint32Array, so the shipped example shows the wrong behaviour too.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions