mirror of
https://github.com/ruby/ruby.git
synced 2022-11-09 12:17:21 -05:00
* lib/base64.rb: make urlsafe mode user-friendly.
* lib/base64.rb (Base64.urlsafe_encode64): a new option "padding" to suppress the padding character ("="). * lib/base64.rb (Base64.urlsafe_decode64): now it accepts not only correctly-padded input but also unpadded input. [Feature #10740][ruby-core:67570] * test/base64/test_base64.rb: Test for above git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@49585 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
This commit is contained in:
parent
b4974e71dc
commit
6b6680945e
4 changed files with 51 additions and 3 deletions
|
@ -77,15 +77,30 @@ module Base64
|
|||
# This method complies with ``Base 64 Encoding with URL and Filename Safe
|
||||
# Alphabet'' in RFC 4648.
|
||||
# The alphabet uses '-' instead of '+' and '_' instead of '/'.
|
||||
def urlsafe_encode64(bin)
|
||||
strict_encode64(bin).tr("+/", "-_")
|
||||
# Note that the result can still contain '='.
|
||||
# You can remove the padding by setting "padding" as false.
|
||||
def urlsafe_encode64(bin, padding: true)
|
||||
str = strict_encode64(bin).tr("+/", "-_")
|
||||
str = str.delete("=") unless padding
|
||||
str
|
||||
end
|
||||
|
||||
# Returns the Base64-decoded version of +str+.
|
||||
# This method complies with ``Base 64 Encoding with URL and Filename Safe
|
||||
# Alphabet'' in RFC 4648.
|
||||
# The alphabet uses '-' instead of '+' and '_' instead of '/'.
|
||||
#
|
||||
# The padding character is optional.
|
||||
# This method accepts both correctly-padded and unpadded input.
|
||||
# Note that it still rejects incorrectly-padded input.
|
||||
def urlsafe_decode64(str)
|
||||
strict_decode64(str.tr("-_", "+/"))
|
||||
# NOTE: RFC 4648 does say nothing about unpadded input, but says that
|
||||
# "the excess pad characters MAY also be ignored", so it is inferred that
|
||||
# unpadded input is also acceptable.
|
||||
str = str.tr("-_", "+/")
|
||||
if !str.end_with?("=") && str.length % 4 != 0
|
||||
str = str.ljust((str.length + 3) & ~3, "=")
|
||||
end
|
||||
strict_decode64(str)
|
||||
end
|
||||
end
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue