-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
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
Adds non-allocating random_bytes method to SecureRandom. Fixes #4049 #4191
Conversation
src/secure_random.cr
Outdated
@@ -69,20 +69,31 @@ module SecureRandom | |||
if n < 0 | |||
raise ArgumentError.new "Negative size: #{n}" | |||
end | |||
buf = Bytes.new(n) |
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.
You could rewrite it to:
Bytes.new(n).tap { |buf| random_bytes(buf) }
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.
done)
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.
This is a good idea. A tiny fix, then good to merge.
@@ -92,7 +101,7 @@ module SecureRandom | |||
@@initialized = true | |||
|
|||
{% if flag?(:linux) %} | |||
if getrandom(Bytes.new(16)) >= 0 | |||
if sys_getrandom(Bytes.new(16)) >= 0 |
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.
This should still call `getrandom, even for 16 bytes. Maybe we could only read 2 bytes at first.
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.
Well, i've saved an old behaviour:
before commit was 1:getrandom(Bytes):Int
that returns number of bytes and 2:getrandom(Int):Bytes
that wraps (1) for arbitrary size.
Now (2) has signature getrandom(Bytes):Nil
, so (1) is renamed to sys_getrandom(Bytes)
to avoid conflict. Here we are checking if getrandom syscall is supported, so sys_getrandom
seems right function for me.
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.
You're right.
Thanks @konovod ! |
Fixes #4049.
I thought that there is a #3434 so i should wait until it is checked, but now i spotted labels so i think this PR should be done.