Class: Keybox::RandomDevice

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

Overview

Use an IO device to retrieve random data. Usually this is somethine like ‘/dev/random’ but may be anything that can read from by IO.read.

bytes = RandomDevice.random_bytes(42)

or

rd = RandomDevice.new
bytes = rd.random_bytes(42)

If there is a some other hardware device or some service that provides random byte stream, set it as the default device in this class and it will use it instead of the default.

my_random_device = RandomDevice("/dev/super-random-device")

or

RandomDevice.default = "/dev/super-random-device"
my_random_device     = RandomDevice.new
my_random_device.source                        # =>  "/dev/super-random-device"

All further instances of RandomDevice will use it as the default.

RandomDevice can either produce random bytes as a class or as an instance.

random_bytes = RandomDevice.random_bytes(42)  
random_bytes.size                              # => 42

Constant Summary collapse

@@DEVICES =
[ "/dev/urandom", "/dev/random" ]
@@DEFAULT =
nil

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(device = nil) ⇒ RandomDevice

Returns a new instance of RandomDevice.



42
43
44
45
46
47
48
# File 'lib/keybox/randomizer.rb', line 42

def initialize(device = nil)
    if not device.nil? and File.readable?(device) then
        @source = device
    else
        @source = RandomDevice.default
    end
end

Instance Attribute Details

#sourceObject

Returns the value of attribute source.



40
41
42
# File 'lib/keybox/randomizer.rb', line 40

def source
  @source
end

Class Method Details

.defaultObject



55
56
57
58
59
60
61
62
63
64
65
# File 'lib/keybox/randomizer.rb', line 55

def default
    return @@DEFAULT unless @@DEFAULT.nil?

    @@DEVICES.each do |device|
        if File.readable?(device) then
            @@DEFAULT = device 
            break
        end
    end
    return @@DEFAULT
end

.default=(device) ⇒ Object



67
68
69
70
71
72
73
74
# File 'lib/keybox/randomizer.rb', line 67

def default=(device)
    if File.readable?(device) then
        @@DEVICES << device
        @@DEFAULT = device
    else
        raise ArgumentError, "device #{device} is not readable and therefore makes a bad random device"
    end
end

.random_bytes(count = 1) ⇒ Object



76
77
78
# File 'lib/keybox/randomizer.rb', line 76

def random_bytes(count = 1)
    File.read(RandomDevice.default,count)
end

Instance Method Details

#random_bytes(count = 1) ⇒ Object



50
51
52
# File 'lib/keybox/randomizer.rb', line 50

def random_bytes(count = 1)
    File.read(source,count)
end