Skip to content

Commit b109397

Browse files
committed
Add SecureRandom.base58
1 parent 82dd93b commit b109397

File tree

3 files changed

+45
-0
lines changed

3 files changed

+45
-0
lines changed

activesupport/CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
* Add `SecureRandom.base58` for generation of random base58 strings.
2+
3+
*Matthew Draper + Guillermo Iguaran*
4+
15
* Add `#prev_day` and `#next_day` counterparts to `#yesterday` and
26
`#tomorrow` for `Date`, `Time`, and `DateTime`.
37

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
module SecureRandom
2+
BASE58_ALPHABET = ('0'..'9').to_a + ('A'..'Z').to_a + ('a'..'z').to_a - ['0', 'O', 'I', 'l']
3+
# SecureRandom.base58 generates a random base58 string.
4+
#
5+
# The argument _n_ specifies the length, of the random string to be generated.
6+
#
7+
# If _n_ is not specified or is nil, 16 is assumed. It may be larger in the future.
8+
#
9+
# The result may contain alphanumeric characters except 0, O, I and l
10+
#
11+
# p SecureRandom.base58 #=> "4kUgL2pdQMSCQtjE"
12+
# p SecureRandom.base58(24) #=> "77TMHrHJFvFDwodq8w7Ev2m7"
13+
#
14+
def self.base58(n = 16)
15+
SecureRandom.random_bytes(n).unpack("C*").map do |byte|
16+
idx = byte % 64
17+
idx = SecureRandom.random_number(58) if idx >= 58
18+
BASE58_ALPHABET[idx]
19+
end.join
20+
end
21+
end
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
require 'abstract_unit'
2+
require 'active_support/core_ext/securerandom'
3+
4+
class SecureRandomTest < ActiveSupport::TestCase
5+
def test_base58
6+
s1 = SecureRandom.base58
7+
s2 = SecureRandom.base58
8+
9+
assert_not_equal s1, s2
10+
assert_equal 16, s1.length
11+
end
12+
13+
def test_base58_with_length
14+
s1 = SecureRandom.base58(24)
15+
s2 = SecureRandom.base58(24)
16+
17+
assert_not_equal s1, s2
18+
assert_equal 24, s1.length
19+
end
20+
end

0 commit comments

Comments
 (0)