mirror of
https://github.com/ruby/ruby.git
synced 2022-11-09 12:17:21 -05:00
* lib/securerandom.rb: use OpenSSL::BN for performance improvement.
* benchmark/bm_securerandom.rb: benchmark script. git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@47104 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
This commit is contained in:
parent
d6f0bd2b84
commit
0a22f4c168
3 changed files with 32 additions and 13 deletions
|
@ -1,3 +1,9 @@
|
|||
Fri Aug 8 01:53:37 2014 Masaki Matsushita <glass.saga@gmail.com>
|
||||
|
||||
* lib/securerandom.rb: use OpenSSL::BN for performance improvement.
|
||||
|
||||
* benchmark/bm_securerandom.rb: benchmark script.
|
||||
|
||||
Fri Aug 8 17:19:57 2014 SHIBATA Hiroshi <shibata.hiroshi@gmail.com>
|
||||
|
||||
* lib/open-uri.rb: remove needless condition for old ruby version.
|
||||
|
|
5
benchmark/bm_securerandom.rb
Normal file
5
benchmark/bm_securerandom.rb
Normal file
|
@ -0,0 +1,5 @@
|
|||
require "securerandom"
|
||||
|
||||
20_0000.times do
|
||||
SecureRandom.random_number(100)
|
||||
end
|
|
@ -214,21 +214,29 @@ module SecureRandom
|
|||
#
|
||||
def self.random_number(n=0)
|
||||
if 0 < n
|
||||
hex = n.to_s(16)
|
||||
hex = '0' + hex if (hex.length & 1) == 1
|
||||
bin = [hex].pack("H*")
|
||||
mask = bin[0].ord
|
||||
mask |= mask >> 1
|
||||
mask |= mask >> 2
|
||||
mask |= mask >> 4
|
||||
begin
|
||||
rnd = SecureRandom.random_bytes(bin.length)
|
||||
rnd[0] = (rnd[0].ord & mask).chr
|
||||
end until rnd < bin
|
||||
rnd.unpack("H*")[0].hex
|
||||
if defined? OpenSSL::BN
|
||||
OpenSSL::BN.rand_range(n).to_i
|
||||
else
|
||||
hex = n.to_s(16)
|
||||
hex = '0' + hex if (hex.length & 1) == 1
|
||||
bin = [hex].pack("H*")
|
||||
mask = bin[0].ord
|
||||
mask |= mask >> 1
|
||||
mask |= mask >> 2
|
||||
mask |= mask >> 4
|
||||
begin
|
||||
rnd = SecureRandom.random_bytes(bin.length)
|
||||
rnd[0] = (rnd[0].ord & mask).chr
|
||||
end until rnd < bin
|
||||
rnd.unpack("H*")[0].hex
|
||||
end
|
||||
else
|
||||
# assumption: Float::MANT_DIG <= 64
|
||||
i64 = SecureRandom.random_bytes(8).unpack("Q")[0]
|
||||
if defined? OpenSSL::BN
|
||||
i64 = OpenSSL::BN.rand(64, -1).to_i
|
||||
else
|
||||
i64 = SecureRandom.random_bytes(8).unpack("Q")[0]
|
||||
end
|
||||
Math.ldexp(i64 >> (64-Float::MANT_DIG), -Float::MANT_DIG)
|
||||
end
|
||||
end
|
||||
|
|
Loading…
Reference in a new issue