|
diff --git a/lib/securerandom.rb b/lib/securerandom.rb
|
|
index 476f5e1..f04c6e2 100644
|
|
--- a/lib/securerandom.rb
|
|
+++ b/lib/securerandom.rb
|
|
@@ -297,4 +297,23 @@ module SecureRandom
|
|
ary[3] = (ary[3] & 0x3fff) | 0x8000
|
|
"%08x-%04x-%04x-%04x-%04x%08x" % ary
|
|
end
|
|
+
|
|
+ # SecureRandom.alphanumeric generates a random alphanumeric string.
|
|
+ #
|
|
+ # The argument _n_ specifies the length, in bytes, of the random number
|
|
+ # to be generated. The length of the result string is about 4/3 of _n_.
|
|
+ #
|
|
+ # If _n_ is not specified or is nil, 16 is assumed.
|
|
+ # It may be larger in the future.
|
|
+ #
|
|
+ # The result may contain A-Z, a-z and 0-9.
|
|
+ #
|
|
+ # p SecureRandom.alphanumeric #=> "2BuBuLf3WfSKyQbRccA"
|
|
+ # p SecureRandom.alphanumeric #=> "6BbW0pxO0YENxn38HMUbcQ"
|
|
+ #
|
|
+ # If a secure random number generator is not available,
|
|
+ # +NotImplementedError+ is raised.
|
|
+ def self.alphanumeric(n=nil)
|
|
+ [random_bytes(n)].pack("m*").delete("\n+/=")
|
|
+ end
|
|
end
|
|
diff --git a/test/test_securerandom.rb b/test/test_securerandom.rb
|
|
index 0a78624..d49d579 100644
|
|
--- a/test/test_securerandom.rb
|
|
+++ b/test/test_securerandom.rb
|
|
@@ -164,6 +164,13 @@ end
|
|
end
|
|
end
|
|
|
|
+ def test_alphanumeric
|
|
+ 65.times do |idx|
|
|
+ an = @it.alphanumeric
|
|
+ assert_match(/^[0-9a-zA-Z]+$/, an)
|
|
+ end
|
|
+ end
|
|
+
|
|
def protect
|
|
begin
|
|
yield
|