Project

General

Profile

Feature #10849 ยป securerandom.txt

Git Diff - andrewcbutterfield@gmail.com (Andrew Butterfield), 02/12/2015 11:56 PM

 
1
diff --git a/lib/securerandom.rb b/lib/securerandom.rb
2
index 476f5e1..f04c6e2 100644
3
--- a/lib/securerandom.rb
4
+++ b/lib/securerandom.rb
5
@@ -297,4 +297,23 @@ module SecureRandom
6
     ary[3] = (ary[3] & 0x3fff) | 0x8000
7
     "%08x-%04x-%04x-%04x-%04x%08x" % ary
8
   end
9
+
10
+  # SecureRandom.alphanumeric generates a random alphanumeric string.
11
+  #
12
+  # The argument _n_ specifies the length, in bytes, of the random number
13
+  # to be generated. The length of the result string is about 4/3 of _n_.
14
+  #
15
+  # If _n_ is not specified or is nil, 16 is assumed.
16
+  # It may be larger in the future.
17
+  #
18
+  # The result may contain A-Z, a-z and 0-9.
19
+  #
20
+  #   p SecureRandom.alphanumeric #=> "2BuBuLf3WfSKyQbRccA"
21
+  #   p SecureRandom.alphanumeric #=> "6BbW0pxO0YENxn38HMUbcQ"
22
+  #
23
+  # If a secure random number generator is not available,
24
+  # +NotImplementedError+ is raised.
25
+  def self.alphanumeric(n=nil)
26
+    [random_bytes(n)].pack("m*").delete("\n+/=")
27
+  end
28
 end
29
diff --git a/test/test_securerandom.rb b/test/test_securerandom.rb
30
index 0a78624..d49d579 100644
31
--- a/test/test_securerandom.rb
32
+++ b/test/test_securerandom.rb
33
@@ -164,6 +164,13 @@ end
34
     end
35
   end
36
 
37
+  def test_alphanumeric
38
+    65.times do |idx|
39
+      an = @it.alphanumeric
40
+      assert_match(/^[0-9a-zA-Z]+$/, an)
41
+    end
42
+  end
43
+
44
   def protect
45
     begin
46
       yield