diff --git a/activesupport/lib/active_support/secure_random.rb b/activesupport/lib/active_support/secure_random.rb index 688165f9a3fcdee65e4a2e977ca6019faedbc8ce..97971e883007e4a07b0ad54b6a3507d4e7b5238a 100644 --- a/activesupport/lib/active_support/secure_random.rb +++ b/activesupport/lib/active_support/secure_random.rb @@ -164,13 +164,13 @@ def self.random_number(n=0) hex = n.to_s(16) hex = '0' + hex if (hex.length & 1) == 1 bin = [hex].pack("H*") - mask = bin[0].ord + mask = bin[0] mask |= mask >> 1 mask |= mask >> 2 mask |= mask >> 4 begin rnd = SecureRandom.random_bytes(bin.length) - rnd[0] = (rnd[0].ord & mask).chr + rnd[0] = rnd[0] & mask end until rnd < bin rnd.unpack("H*")[0].hex else diff --git a/activesupport/test/secure_random_test.rb b/activesupport/test/secure_random_test.rb index b0b6c21a81b4a407019497a3b2a81015710f8262..44694cd811baf2a6ce8ab2fdfa5b0576a10e5678 100644 --- a/activesupport/test/secure_random_test.rb +++ b/activesupport/test/secure_random_test.rb @@ -12,4 +12,8 @@ def test_hex b2 = ActiveSupport::SecureRandom.hex(64) assert_not_equal b1, b2 end + + def test_random_number + assert ActiveSupport::SecureRandom.random_number(5000) < 5000 + end end