require 'base64' module RightSupport::Data # Implements the base64url encoding mechanism as described in RFC7515: JSON # Web Signature (JWS). # # This encoding is similar to base64, but omits newlines and padding # `=` characters, and uses the `-` and `_` characters in place of the `+` and # `/` characters. This makes it suitable for use inside URLs, cookies, and # other "webby" contexts where we want to avoid text expansion due to URL # encoding. module Base64URL # @param [String] str ASCII string to encode # @return [String] base64 representation of str def self.encode(text) Base64.encode64(text).tr('+/', '-_').gsub(/[\n=]/, '') end # @param [String] str base64 to decode to ASCII # @return [String] plain ASCII def self.decode(b64) b64 = b64.dup b64 += '=' * (4 - b64.length.modulo(4)) Base64.decode64(b64.tr('-_', '+/')) end end end