Class: SecureRandom

Inherits:
Object
  • Object
show all
Defined in:
lib/interfacets/client/utils/securerandom.rb

Class Method Summary collapse

Class Method Details

.base64(n = nil) ⇒ Object



31
32
33
# File 'lib/interfacets/client/utils/securerandom.rb', line 31

def base64(n=nil)
  [random_bytes(n)].pack("m*").gsub("\n", "")
end

.hex(n = nil) ⇒ Object



27
28
29
# File 'lib/interfacets/client/utils/securerandom.rb', line 27

def hex(n=nil)
  random_bytes(n).unpack("H*")[0]
end

.random_bytes(n = nil) ⇒ Object

Raises:

  • (NotImplementedError)


7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/interfacets/client/utils/securerandom.rb', line 7

def random_bytes(n=nil)
  n = n ? n.to_int : 16

  # Need to read more than the number of bytes because sometimes it comes
  # back as less. Not sure why, but whatever.
  begin
    File.open("/dev/urandom", 'r') {|f|
      ret = f.read(n*2)
      unless ret.length > n
        raise NotImplementedError, "Unexpected partial read from random device: only #{ret.length} for #{n} bytes"
      end
      return ret[0..n]
    }
  rescue
    raise File::NoFileError, "No random device"
  end

  raise NotImplementedError, "No random device"
end

.random_number(n = 0) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/interfacets/client/utils/securerandom.rb', line 41

def random_number(n=0)
  if 0 < n
    hex = n.to_s(16)
    hex = '0' + hex if (hex.length & 1) == 1
    bin = [hex].pack("H*")
    mask = bin[0].ord
    mask |= mask >> 1
    mask |= mask >> 2
    mask |= mask >> 4

    loop do
      rnd = random_bytes(bin.length)
      rnd[0] = (rnd[0].ord & mask).chr
      return rnd.unpack("H*")[0].hex if rnd < bin
    end
  else
    raise NotImplementedError
  end
end

.urlsafe_base64(n = nil, padding = false) ⇒ Object



35
36
37
38
39
# File 'lib/interfacets/client/utils/securerandom.rb', line 35

def urlsafe_base64(n=nil, padding=false)
  s = base64.gsub("+", "-").gsub("/", "_")
  s.gsub!("=", "") unless padding
  s
end

.uuid ⇒ Object



61
62
63
64
65
66
# File 'lib/interfacets/client/utils/securerandom.rb', line 61

def uuid
  ary = random_bytes(16).unpack("nnnnnnnn")
  ary[3] = (ary[3] & 0x0fff) | 0x4000
  ary[4] = (ary[4] & 0x3fff) | 0x8000
  "%04x%04x-%04x-%04x-%04x-%04x%04x%04x" % ary
end