Project

General

Profile

Bug #4579 ยป securerandom_opensslfree.diff

nahi (Hiroshi Nakamura), 06/11/2011 06:36 PM

View differences:

lib/securerandom.rb (working copy)
5 5
#
6 6
# It supports following secure random number generators.
7 7
#
8
# * openssl
9 8
# * /dev/urandom
10 9
# * Win32
11 10
#
......
33 32
# p SecureRandom.random_bytes(10) #=> "\323U\030TO\234\357\020\a\337"
34 33
# ...
35 34

  
36
begin
37
  require 'openssl'
38
rescue LoadError
39
end
40

  
41 35
module SecureRandom
42 36
  # SecureRandom.random_bytes generates a random binary string.
43 37
  #
......
56 50
  def self.random_bytes(n=nil)
57 51
    n ||= 16
58 52

  
59
    if defined? OpenSSL::Random
60
      return OpenSSL::Random.random_bytes(n)
61
    end
62

  
63 53
    if !defined?(@has_urandom) || @has_urandom
64 54
      flags = File::RDONLY
65 55
      flags |= File::NONBLOCK if defined? File::NONBLOCK
test/test_securerandom.rb (revision 0)
1
require 'test/unit'
2
require 'securerandom'
3

  
4
class TestSecureRandom < Test::Unit::TestCase
5
  def setup
6
    @it = SecureRandom
7
  end
8

  
9
  def test_s_random_bytes
10
    assert_equal(16, @it.random_bytes.size)
11
    assert_equal(Encoding::ASCII_8BIT, @it.random_bytes.encoding)
12
    65.times do |idx|
13
      assert_equal(idx, @it.random_bytes(idx).size)
14
    end
15
  end
16

  
17
  def test_s_hex
18
    assert_equal(16 * 2, @it.hex.size)
19
    33.times do |idx|
20
      assert_equal(idx * 2, @it.hex(idx).size)
21
      assert_equal(idx, @it.hex(idx).gsub(/(..)/) { [$1].pack('H*') }.size)
22
    end
23
  end
24

  
25
  def test_s_base64
26
    assert_equal(16, @it.base64.unpack('m*')[0].size)
27
    17.times do |idx|
28
      assert_equal(idx, @it.base64(idx).unpack('m*')[0].size)
29
    end
30
  end
31

  
32
  def test_s_urlsafe_base64
33
    safe = /[\n+\/]/
34
    65.times do |idx|
35
      assert_not_match(safe, @it.urlsafe_base64(idx))
36
    end
37
    # base64 can include unsafe byte
38
    10000.times do |idx|
39
      return if safe =~ @it.base64(idx)
40
    end
41
    flunk
42
  end
43

  
44
  def test_s_random_number_float
45
    100.times do
46
      v = @it.random_number
47
      assert(0.0 <= v && v < 1.0)
48
    end
49
  end
50

  
51
  def test_s_random_number_float_by_zero
52
    100.times do
53
      v = @it.random_number(0)
54
      assert(0.0 <= v && v < 1.0)
55
    end
56
  end
57

  
58
  def test_s_random_number_int
59
    100.times do |idx|
60
      next if idx.zero?
61
      v = @it.random_number(idx)
62
      assert(0 <= v && v < idx)
63
    end
64
  end
65

  
66
  def test_uuid
67
    assert_equal([8, 4, 4, 4, 8], @it.uuid.unpack('a8xa4xa4xa4xa8').map { |e| e.size })
68
  end
69

  
70
  def protect
71
    begin
72
      yield
73
    rescue NotImplementedError
74
      # ignore
75
    end
76
  end
77
end