Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Why isn't crypto.getRandomValues accept a data view? #284

Open
amn opened this issue Sep 24, 2021 · 1 comment
Open

Why isn't crypto.getRandomValues accept a data view? #284

amn opened this issue Sep 24, 2021 · 1 comment

Comments

@amn
Copy link

amn commented Sep 24, 2021

I struggle to understand why crypto.getRandomValues doesn't accept a DataView object?

Indeed, the spec. says:

If array is not an Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, BigInt64Array, or BigUint64Array, then throw a TypeMismatchError and terminate the algorithm.

Is there any reason why DataView isn't among these acceptable classes of objects? Does the procedure actually utilize different writing granularity depending on what kind of typed array it is provided, and hence it wouldn't be meaningful for it to work with a view? It could access the underlying buffer anyway, wouldn't it? I mean, this would certainly be implementation defined -- how the procedure loads the underlying buffer with the random data -- but can't a case be made that if all of the above are allowed, principally providing access to an underlying buffer, then so should be DataView? That's what it's for, isn't it? On that note, even passing ArrayBuffer could be acceptable then, on the same argument, no?

Apologies if I have missed something obvious.

@twiss
Copy link
Member

twiss commented Sep 27, 2021

The main reason why the spec accepts the types it does is that, when interpreting random bytes as floats, you'll get non-uniform random values, which may be unexpected. E.g., imagine someone does

crypto.getRandomValues(dataView);
dataView.getFloat32(0);

at first glance, you might expect this to produce a (uniformly) random float32.
By contrast,

crypto.getRandomValues(uint8Array);
new DataView(uint8Array.buffer).getFloat32(0);

should make it clear that we're interpreting random bytes as floats, and hopefully raise some questions about whether that's correct.
(Of course, when you're not using getFloat32/64 / Float32/64Array, then there's no issue, but the spec can't know that.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants