diff options
author | Guillermo Iguaran <guilleiguaran@gmail.com> | 2015-01-09 17:51:23 -0500 |
---|---|---|
committer | Guillermo Iguaran <guilleiguaran@gmail.com> | 2015-01-09 17:51:46 -0500 |
commit | b1093977110f18ae0cafe56c3d99fc22a7d54d1b (patch) | |
tree | 08c688fd107285d218eae5256fffcdffdb3620b1 /activesupport | |
parent | 82dd93bd5eb6613c6fd8ba0725b30c273aba7008 (diff) | |
download | rails-b1093977110f18ae0cafe56c3d99fc22a7d54d1b.tar.gz rails-b1093977110f18ae0cafe56c3d99fc22a7d54d1b.tar.bz2 rails-b1093977110f18ae0cafe56c3d99fc22a7d54d1b.zip |
Add SecureRandom.base58
Diffstat (limited to 'activesupport')
-rw-r--r-- | activesupport/CHANGELOG.md | 4 | ||||
-rw-r--r-- | activesupport/lib/active_support/core_ext/securerandom.rb | 21 | ||||
-rw-r--r-- | activesupport/test/core_ext/securerandom.rb | 20 |
3 files changed, 45 insertions, 0 deletions
diff --git a/activesupport/CHANGELOG.md b/activesupport/CHANGELOG.md index 2756f7e0e2..a7306c2cae 100644 --- a/activesupport/CHANGELOG.md +++ b/activesupport/CHANGELOG.md @@ -1,3 +1,7 @@ +* Add `SecureRandom.base58` for generation of random base58 strings. + + *Matthew Draper + Guillermo Iguaran* + * Add `#prev_day` and `#next_day` counterparts to `#yesterday` and `#tomorrow` for `Date`, `Time`, and `DateTime`. diff --git a/activesupport/lib/active_support/core_ext/securerandom.rb b/activesupport/lib/active_support/core_ext/securerandom.rb new file mode 100644 index 0000000000..394cc76b98 --- /dev/null +++ b/activesupport/lib/active_support/core_ext/securerandom.rb @@ -0,0 +1,21 @@ +module SecureRandom + BASE58_ALPHABET = ('0'..'9').to_a + ('A'..'Z').to_a + ('a'..'z').to_a - ['0', 'O', 'I', 'l'] + # SecureRandom.base58 generates a random base58 string. + # + # The argument _n_ specifies the length, of the random string to be generated. + # + # If _n_ is not specified or is nil, 16 is assumed. It may be larger in the future. + # + # The result may contain alphanumeric characters except 0, O, I and l + # + # p SecureRandom.base58 #=> "4kUgL2pdQMSCQtjE" + # p SecureRandom.base58(24) #=> "77TMHrHJFvFDwodq8w7Ev2m7" + # + def self.base58(n = 16) + SecureRandom.random_bytes(n).unpack("C*").map do |byte| + idx = byte % 64 + idx = SecureRandom.random_number(58) if idx >= 58 + BASE58_ALPHABET[idx] + end.join + end +end diff --git a/activesupport/test/core_ext/securerandom.rb b/activesupport/test/core_ext/securerandom.rb new file mode 100644 index 0000000000..dfacb7fe9f --- /dev/null +++ b/activesupport/test/core_ext/securerandom.rb @@ -0,0 +1,20 @@ +require 'abstract_unit' +require 'active_support/core_ext/securerandom' + +class SecureRandomTest < ActiveSupport::TestCase + def test_base58 + s1 = SecureRandom.base58 + s2 = SecureRandom.base58 + + assert_not_equal s1, s2 + assert_equal 16, s1.length + end + + def test_base58_with_length + s1 = SecureRandom.base58(24) + s2 = SecureRandom.base58(24) + + assert_not_equal s1, s2 + assert_equal 24, s1.length + end +end |