Module: SecureRandom
| Relationships & Source Files | |
| Super Chains via Extension / Inclusion / Inheritance | |
|
Class Chain:
self,
Random::Formatter
|
|
| Defined in: | lib/securerandom.rb |
Overview
Secure random number generator interface.
This library is an interface to secure random number generators which are suitable for generating session keys in HTTP cookies, etc.
You can use this library in your application by requiring it:
require 'securerandom'
It supports the following secure random number generators:
-
openssl
-
/dev/urandom
-
Win32
SecureRandom is extended by the Random::Formatter module which defines the following methods:
-
alphanumeric
-
base64
-
choose
-
gen_random
-
hex
-
rand
-
random_bytes
-
random_number
-
urlsafe_base64
-
uuid
These methods are usable as class methods of SecureRandom such as SecureRandom.hex.
If a secure random number generator is not available, NotImplementedError is raised.
Constant Summary
-
VERSION =
# File 'lib/securerandom.rb', line 44
The version
"0.4.1"
Class Method Summary
-
.alphanumeric(n = nil, chars: ALPHANUMERIC)
Compatibility methods for Ruby 3.2, we can remove this after dropping to support Ruby 3.2.
-
.bytes(n)
Returns a random binary string containing
sizebytes. -
.gen_random_openssl(n)
private
Internal use only
Implementation using OpenSSL.
-
.gen_random_urandom(n)
private
Internal use only
Implementation using system random device.
Class Method Details
.alphanumeric(n = nil, chars: ALPHANUMERIC)
Compatibility methods for Ruby 3.2, we can remove this after dropping to support Ruby 3.2
# File 'lib/securerandom.rb', line 55
def alphanumeric(n = nil, chars: ALPHANUMERIC) n = 16 if n.nil? choose(chars, n) end
.bytes(n)
Returns a random binary string containing size bytes.
See Random.bytes
# File 'lib/securerandom.rb', line 50
def bytes(n) return gen_random(n) end
.gen_random_openssl(n) (private)
Implementation using OpenSSL
# File 'lib/securerandom.rb', line 65
def gen_random_openssl(n) return OpenSSL::Random.random_bytes(n) end
.gen_random_urandom(n) (private)
Implementation using system random device
# File 'lib/securerandom.rb', line 70
def gen_random_urandom(n) ret = Random.urandom(n) unless ret raise NotImplementedError, "No random device" end unless ret.length == n raise NotImplementedError, "Unexpected partial read from random device: only #{ret.length} for #{n} bytes" end ret end