* lib/securerandom.rb (SecureRandom.urlsafe_base64): add optional

argument to add padding.


git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@22801 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
This commit is contained in:
akr 2009-03-06 14:36:33 +00:00
parent e2421845df
commit 42d25de958
2 changed files with 18 additions and 6 deletions

View File

@ -1,3 +1,8 @@
Fri Mar 6 23:35:59 2009 Tanaka Akira <akr@fsij.org>
* lib/securerandom.rb (SecureRandom.urlsafe_base64): add optional
argument to add padding.
Fri Mar 6 19:25:40 2009 Nobuyoshi Nakada <nobu@ruby-lang.org>
* configure.in (RUBY_LIB_VERSION_STYLE): sets full or minor style

View File

@ -156,28 +156,35 @@ module SecureRandom
# SecureRandom.urlsafe_base64 generates a random URL-safe base64 string.
#
# The argument n specifies the length of the random length.
# The length of the result string is about 4/3 of n.
# The argument _n_ specifies the length of the random length.
# The length of the result string is about 4/3 of _n_.
#
# If n is not specified, 16 is assumed.
# If _n_ is not specified, 16 is assumed.
# It may be larger in future.
#
# No padding is generated because "=" may be used as a URL delimiter.
# The boolean argument _padding_ specifies the padding.
# If it is false or nil, padding is not generated.
# Otherwise padding is generated.
# By default, padding is not generated because "=" may be used as a URL delimiter.
#
# The result may contain A-Z, a-z, 0-9, "-" and "_".
# "=" is also used if _padding_ is true.
#
# p SecureRandom.urlsafe_base64 #=> "b4GOKm4pOYU_-BOXcrUGDg"
# p SecureRandom.urlsafe_base64 #=> "UZLdOkzop70Ddx-IJR0ABg"
#
# p SecureRandom.urlsafe_base64(nil, true) #=> "i0XQ-7gglIsHGV2_BNPrdQ=="
# p SecureRandom.urlsafe_base64(nil, true) #=> "-M8rLhr7JEpJlqFGUMmOxg=="
#
# If secure random number generator is not available,
# NotImplementedError is raised.
#
# See RFC 3548 for URL-safe base64.
def self.urlsafe_base64(n=nil)
def self.urlsafe_base64(n=nil, padding=false)
s = [random_bytes(n)].pack("m*")
s.delete!("\n")
s.tr!("+/", "-_")
s.delete!("=")
s.delete!("=") if !padding
s
end