Module: Sysrandom
- Defined in:
- lib/sysrandom.rb,
lib/sysrandom/version.rb,
ext/sysrandom/sysrandom_ext.c
Overview
Secure random number generation using system RNG facilities
Constant Summary collapse
- DEFAULT_LENGTH =
For some reason SecureRandom defaults to 16 bytes
16
- VERSION =
"1.0.4".freeze
Class Method Summary collapse
- .__random_uint32 ⇒ Object
- .base64(n = nil) ⇒ Object
- .hex(n = nil) ⇒ Object
- .random_bytes ⇒ Object
- .random_number(n = 0) ⇒ Object
- .urlsafe_base64(n = nil, padding = false) ⇒ Object
- .uuid ⇒ Object
Instance Method Summary collapse
-
#__random_uint32 ⇒ Object
Random uint32, used by random_number.
- #random_bytes(n = nil) ⇒ Object
Class Method Details
.__random_uint32 ⇒ Object
9 |
# File 'ext/sysrandom/sysrandom_ext.c', line 9 static VALUE Sysrandom_random_uint32(VALUE self); |
.base64(n = nil) ⇒ Object
53 54 55 |
# File 'lib/sysrandom.rb', line 53 def base64(n = nil) Base64.encode64(random_bytes(n)).chomp end |
.hex(n = nil) ⇒ Object
62 63 64 |
# File 'lib/sysrandom.rb', line 62 def hex(n = nil) random_bytes(n).unpack("h*").first end |
.random_bytes ⇒ Object
10 |
# File 'ext/sysrandom/sysrandom_ext.c', line 10
static VALUE Sysrandom_random_bytes(int argc, VALUE *argv, VALUE self);
|
.random_number(n = 0) ⇒ Object
42 43 44 45 46 47 48 49 50 51 |
# File 'lib/sysrandom.rb', line 42 def random_number(n = 0) result = __random_uint32 / (2**32).to_f if n <= 0 result else result *= n n.is_a?(Fixnum) ? result.floor : result end end |
.urlsafe_base64(n = nil, padding = false) ⇒ Object
57 58 59 60 |
# File 'lib/sysrandom.rb', line 57 def urlsafe_base64(n = nil, padding = false) result = Base64.urlsafe_encode64(random_bytes(n)).chomp padding ? result : result.tr("=", "") end |
.uuid ⇒ Object
66 67 68 69 |
# File 'lib/sysrandom.rb', line 66 def uuid values = hex(16).match(/\A(.{8})(.{4})(.)(.{3})(.)(.{3})(.{12})\z/) "#{values[1]}-#{values[2]}-4#{values[4]}-#{'89ab'[values[5].ord % 4]}#{values[6]}-#{values[7]}" end |
Instance Method Details
#__random_uint32 ⇒ Object
Random uint32, used by random_number. The C extension provides an equivalent method
25 26 27 |
# File 'lib/sysrandom.rb', line 25 def __random_uint32 @_java_secure_random.nextLong & 0xFFFFFFFF end |
#random_bytes(n = nil) ⇒ Object
10 11 12 13 14 15 16 17 18 |
# File 'ext/sysrandom/sysrandom_ext.c', line 10 def random_bytes(n = nil) n ||= DEFAULT_LENGTH raise ArgumentError, "negative string size" if n < 0 return "" if n == 0 bytes = Java::byte[n].new @_java_secure_random.nextBytes(bytes) String.from_java_bytes(bytes) end |