Class: Keybox::RandomSource

Inherits:
Object
  • Object
show all
Defined in:
lib/keybox/randomizer.rb

Overview

A RandomSource uses one from a set of possible source class/modules. So long as the @@DEFAULT item responds to random_bytes it is fine.

RandomSource supplies a rand method in the same vein as Kernel#rand.

Constant Summary collapse

@@SOURCE_CLASSES =
[ ::Keybox::RandomDevice, ::OpenSSL::Random ]
@@SOURCE =
nil

Class Method Summary collapse

Class Method Details

.rand(max = nil) ⇒ Object

Behave like Kernel#rand where if no max is specified return a value >= 0.0 but < 1.0.

If a max is specified, return an Integer between 0 and upto but not including max.



131
132
133
134
135
136
137
138
# File 'lib/keybox/randomizer.rb', line 131

def rand(max = nil)
    bytes = source.random_bytes(8)
    num = bytes.unpack("F").first.abs / Float::MAX
    if max then
        num = bytes.unpack("Q").first % max.floor
    end
    return num
end

.register(klass) ⇒ Object



96
97
98
99
100
101
102
# File 'lib/keybox/randomizer.rb', line 96

def register(klass)
    if klass.respond_to?("random_bytes") then 
        @@SOURCE_CLASSES << klass unless @@SOURCE_CLASSES.include?(klass)
    else
        raise ArgumentError, "class #{klass.name} does not have a 'random_bytes' method"
    end
end

.sourceObject



113
114
115
116
117
118
119
120
121
122
# File 'lib/keybox/randomizer.rb', line 113

def source
    return @@SOURCE unless @@SOURCE.nil? or not @@SOURCE_CLASSES.include?(@@SOURCE)
    @@SOURCE_CLASSES.each do |klass|
        if klass.random_bytes(2).length == 2 then
            RandomSource.source = klass
            break
        end
    end
    @@SOURCE
end

.source=(klass) ⇒ Object



108
109
110
111
# File 'lib/keybox/randomizer.rb', line 108

def source=(klass)
    register(klass)
    @@SOURCE = klass
end

.source_classesObject



104
105
106
# File 'lib/keybox/randomizer.rb', line 104

def source_classes
    @@SOURCE_CLASSES
end