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.1".freeze
Class Method Summary collapse
- .__random_uint32 ⇒ Object
- .base64(n = DEFAULT_LENGTH) ⇒ Object
- .hex(n = DEFAULT_LENGTH) ⇒ Object
- .random_bytes ⇒ Object
- .random_number(n = 0) ⇒ Object
- .urlsafe_base64(n = DEFAULT_LENGTH) ⇒ Object
- .uuid ⇒ Object
Instance Method Summary collapse
-
#__random_uint32 ⇒ Object
Random uint32, used by random_number.
- #random_bytes(n = DEFAULT_LENGTH) ⇒ 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 = DEFAULT_LENGTH) ⇒ Object
51 52 53 |
# File 'lib/sysrandom.rb', line 51 def base64(n = DEFAULT_LENGTH) Base64.encode64(random_bytes(n)).chomp end |
.hex(n = DEFAULT_LENGTH) ⇒ Object
59 60 61 |
# File 'lib/sysrandom.rb', line 59 def hex(n = DEFAULT_LENGTH) 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
40 41 42 43 44 45 46 47 48 49 |
# File 'lib/sysrandom.rb', line 40 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 = DEFAULT_LENGTH) ⇒ Object
55 56 57 |
# File 'lib/sysrandom.rb', line 55 def urlsafe_base64(n = DEFAULT_LENGTH) Base64.urlsafe_encode64(random_bytes(n)).chomp end |
.uuid ⇒ Object
63 64 65 66 |
# File 'lib/sysrandom.rb', line 63 def uuid values = SecureRandom.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 = DEFAULT_LENGTH) ⇒ Object
10 11 12 13 14 15 16 |
# File 'ext/sysrandom/sysrandom_ext.c', line 10 def random_bytes(n = DEFAULT_LENGTH) raise ArgumentError, "negative string size" if n < 0 bytes = Java::byte[n].new @_java_secure_random.nextBytes(bytes) String.from_java_bytes(bytes) end |