Method: SuperRandom#bytes

Defined in:
lib/super_random/super_random.rb

#bytes(n = 32) ⇒ Object


11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/super_random/super_random.rb', line 11

def bytes(n=32)
  @randomness = 0

  r1 = RealRand::RandomOrg.new
  r2 = RealRand::EntropyPool.new
  r3 = RealRand::FourmiLab.new

  a1 = a2 = a3 = nil

  t1 = Thread.new{ a1 = r1.randbyte(n) }
  t2 = Thread.new{ a2 = r2.randbyte(n) }
  t3 = Thread.new{ a3 = r3.randbyte(n) }

  begin
    Timeout.timeout(@first_timeout) do
      # Initially, would like to get them all.
      t1.join and t2.join and t3.join
    end
  rescue Timeout::Error
    begin
      Timeout.timeout(@second_timeout) do
        # But at this point,
        # would like to get at least one.
        while a1.nil? and a2.nil? and a3.nil? and (t1.alive? or t2.alive? or t3.alive?)
          Thread.pass
        end
      end
    rescue Timeout::Error
      # If we don't care that we got nothing, go on.
      raise $! unless @nevermind
    end
  end

  a = n.times.inject([]){|a,i|a.push(SecureRandom.random_number(256))}

  [a1, a2, a3].each do |b|
    if b
      @randomness += 1
      n.times{|i|a[i]=(a[i]+b[i])%256}
    end
  end

  return a
end