summaryrefslogtreecommitdiff
path: root/lib/securerandom.rb
diff options
context:
space:
mode:
authornobu <nobu@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>2015-02-14 03:20:04 +0000
committernobu <nobu@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>2015-02-14 03:20:04 +0000
commitb1adbd14e5b197596636f927c03ff132299ab6b6 ()
tree587e44dc967e33e900c4d46fc3bd49697d79a718 /lib/securerandom.rb
parent1f13a179d303c1470f3e76656d14d24cf035fff4 (diff)
random.c: rand_random_number
* random.c (rand_random_number): add a method to return a random number like SecureRandom to Random::Formatter. * lib/securerandom.rb (random_bytes): move to Random::Formatter, the base method of the module. git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@49596 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
-rw-r--r--lib/securerandom.rb47
1 files changed, 27 insertions, 20 deletions
@@ -47,26 +47,6 @@ end
#
module SecureRandom
-
- # SecureRandom.random_bytes generates a random binary string.
- #
- # The argument _n_ specifies the length of the result string.
- #
- # If _n_ is not specified or is nil, 16 is assumed.
- # It may be larger in future.
- #
- # The result may contain any byte: "\x00" - "\xff".
- #
- # p SecureRandom.random_bytes #=> "\xD8\\\xE0\xF4\r\xB2\xFC*WM\xFF\x83\x18\xF45\xB6"
- # p SecureRandom.random_bytes #=> "m\xDC\xFC/\a\x00Uf\xB2\xB2P\xBD\xFF6S\x97"
- #
- # If a secure random number generator is not available,
- # +NotImplementedError+ is raised.
- def self.random_bytes(n=nil)
- n = n ? n.to_int : 16
- gen_random(n)
- end
-
if defined? OpenSSL::Random
def self.gen_random(n)
@pid = 0 unless defined?(@pid)
@@ -94,6 +74,26 @@ module SecureRandom
end
module Random::Formatter
# SecureRandom.hex generates a random hexadecimal string.
#
# The argument _n_ specifies the length, in bytes, of the random number to be generated.
@@ -168,6 +168,7 @@ module Random::Formatter
s
end
# SecureRandom.random_number generates a random number.
#
# If a positive integer is given as _n_,
@@ -212,6 +213,7 @@ module Random::Formatter
Math.ldexp(i64 >> (64-Float::MANT_DIG), -Float::MANT_DIG)
end
end
# SecureRandom.uuid generates a random v4 UUID (Universally Unique IDentifier).
#
@@ -230,6 +232,11 @@ module Random::Formatter
ary[3] = (ary[3] & 0x3fff) | 0x8000
"%08x-%04x-%04x-%04x-%04x%08x" % ary
end
end
SecureRandom.extend(Random::Formatter)