-
Notifications
You must be signed in to change notification settings - Fork 42
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
Modify random_get to use crypto.getRandomValues #75
Conversation
src/wasi.ts
Outdated
buffer8[buf + i] = (Math.random() * 256) | 0; | ||
const end = buf + buf_len; | ||
|
||
if (self.hasCrypto) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can you check "crypto" in globalThis
instead and not cache it in an instance variable?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I tried, but it didn't pass the tests. Looks like globalThis
doesn't exist on all environments 😞
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Also, caching it is most probably faster than checking every time random_get
gets called
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Did it fail in node.js? Maybe the node.js version that was used is too old? globalThis
is supposed to work in all environments. It was introduced as way to unify window
, self
and global
across the various javascript environments.
As for performance, if random_get
is called rarely a tiny slowdown shouldn't matter and if it is called frequently, I would expect the JIT to optimize it down to a couple instructions max, which is much less than even the overhead of making a native call, let alone actually running the PRNG.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I remembered it failing on some test, but it seems I was mistaken. I've pushed the uncached "crypto" in globalThis
version.
Thanks! |
I simply modified the
random_get
implementation to usecrypto.getRandomValues
to generate the random numbers.This has the benefit that the RNG is cryptographically secure, and is probably faster that the previous implementation (though that should be benchmarked).