/
urandom.cr
35 lines (29 loc) · 907 Bytes
/
urandom.cr
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# TODO: replace with `flag?(:unix) && !flag?(:openbsd) && !flag?(:linux)` after crystal > 0.22.0 is released
{% skip_file() if flag?(:openbsd) && flag?(:linux) %}
module Crystal::System::Random
@@initialized = false
private def self.init
@@initialized = true
if File.stat("/dev/urandom").chardev?
@@urandom = urandom = File.open("/dev/urandom", "r")
urandom.close_on_exec = true
urandom.sync = true # don't buffer bytes
end
end
def self.random_bytes(buf : Bytes) : Nil
init unless @@initialized
if urandom = @@urandom
urandom.read_fully(buf)
else
raise "Failed to access secure source to generate random bytes!"
end
end
def self.next_u : UInt8
init unless @@initialized
if urandom = @@urandom
urandom.read_bytes(UInt8)
else
raise "Failed to access secure source to generate random bytes!"
end
end
end