summaryrefslogtreecommitdiff
path: root/lib
diff options
context:
space:
mode:
authornobu <nobu@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>2014-11-09 03:16:24 +0000
committernobu <nobu@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>2014-11-09 03:16:24 +0000
commit93ccab82c55f36fc2e5aee2b53cbc90f56bb94a0 (patch)
treef9bc1993b6f5a1704cb354cc154128ed972335ae /lib
parent0066d95fd6b679a90ba8e62d17e535127e3a4860 (diff)
securerandom.rb: separate implementations
* lib/securerandom.rb (SecureRandom.gen_random): separate implementation details and select at the load time. git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@48334 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
Diffstat (limited to 'lib')
-rw-r--r--lib/securerandom.rb29
1 files changed, 15 insertions, 14 deletions
diff --git a/lib/securerandom.rb b/lib/securerandom.rb
index 6319c2cd89..3e932f6b0e 100644
--- a/lib/securerandom.rb
+++ b/lib/securerandom.rb
@@ -107,8 +107,11 @@ module SecureRandom
# NotImplementedError is raised.
def self.random_bytes(n=nil)
n = n ? n.to_int : 16
+ gen_random(n)
+ end
- if defined? OpenSSL::Random
+ if defined? OpenSSL::Random
+ def self.gen_random(n)
@pid = 0 unless defined?(@pid)
pid = $$
unless @pid == pid
@@ -119,21 +122,25 @@ module SecureRandom
end
return OpenSSL::Random.random_bytes(n)
end
-
- if defined?(AdvApi32)
+ elsif defined?(AdvApi32)
+ def self.gen_random(n)
return AdvApi32.gen_random(n)
end
- if !defined?(@has_urandom) || @has_urandom
+ def self.lastWin32ErrorMessage # :nodoc:
+ # for compatibility
+ return Kernel32.last_error_message
+ end
+ else
+ def self.gen_random(n)
flags = File::RDONLY
flags |= File::NONBLOCK if defined? File::NONBLOCK
flags |= File::NOCTTY if defined? File::NOCTTY
begin
File.open("/dev/urandom", flags) {|f|
unless f.stat.chardev?
- raise Errno::ENOENT
+ break
end
- @has_urandom = true
ret = f.read(n)
unless ret.length == n
raise NotImplementedError, "Unexpected partial read from random device: only #{ret.length} for #{n} bytes"
@@ -141,11 +148,10 @@ module SecureRandom
return ret
}
rescue Errno::ENOENT
- @has_urandom = false
end
- end
- raise NotImplementedError, "No random device"
+ raise NotImplementedError, "No random device"
+ end
end
# SecureRandom.hex generates a random hexadecimal string.
@@ -284,9 +290,4 @@ module SecureRandom
ary[3] = (ary[3] & 0x3fff) | 0x8000
"%08x-%04x-%04x-%04x-%04x%08x" % ary
end
-
- def self.lastWin32ErrorMessage # :nodoc:
- # for compatibility
- Kernel32.last_error_message
- end
end