| 1 | package MIME::Base64; | ||
| 2 | use strict; | ||
| 3 | |||
| 4 | # See: https://developer.mozilla.org/en/docs/Web/API/WindowBase64/Base64_encoding_and_decoding#Solution_.232_.E2.80.93_rewriting_atob()_and_btoa()_using_TypedArrays_and_UTF-8 | ||
| 5 | |||
| 6 | JS::inline(q! | ||
| 7 | var btoa = require('btoa'); | ||
| 8 | var atob = require('atob'); | ||
| 9 | !); | ||
| 10 | |||
| 11 | # encode_base64( $bytes ) | ||
| 12 | # encode_base64( $bytes, $eol ); | ||
| 13 | # Encode data by calling the encode_base64() function. The first argument is the byte string to encode. | ||
| 14 | # The second argument is the line-ending sequence to use. It is optional and defaults to "\n". The | ||
| 15 | # returned encoded string is broken into lines of no more than 76 characters each and it will end with | ||
| 16 | # $eol unless it is empty. Pass an empty string as second argument if you do not want the encoded string | ||
| 17 | # to be broken into lines. | ||
| 18 | # | ||
| 19 | # The function will croak with "Wide character in subroutine entry" if $bytes contains characters with | ||
| 20 | # code above 255. The base64 encoding is only defined for single-byte characters. Use the Encode module | ||
| 21 | # to select the byte encoding you want. | ||
| 22 | sub encode_base64 { | ||
| 23 | my $s = shift; | ||
| 24 | my $eol = shift // "\n"; | ||
| 25 | my $result = JS::inline("btoa(v_s)"); | ||
| 26 | my @out; | ||
| 27 | while ($result) { | ||
| 28 | push @out, substr($result, 0, 76); | ||
| 29 | $result = substr($result, 76); | ||
| 30 | } | ||
| 31 | return join($eol, @out) . $eol; | ||
| 32 | } | ||
| 33 | |||
| 34 | # decode_base64( $str ) | ||
| 35 | # Decode a base64 string by calling the decode_base64() function. This function takes a single argument | ||
| 36 | # which is the string to decode and returns the decoded data. | ||
| 37 | # | ||
| 38 | # Any character not part of the 65-character base64 subset is silently ignored. Characters occurring | ||
| 39 | # after a '=' padding character are never decoded. | ||
| 40 | sub decode_base64 { | ||
| 41 | my $s = shift; | ||
| 42 | my $end = index($s, "="); | ||
| 43 | if ($end >= 0) { | ||
| 44 | $s = substr($s, 0, $end); | ||
| 45 | } | ||
| 46 | my $result = JS::inline("atob(v_s)"); | ||
| 47 | return $result; | ||
| 48 | } | ||
| 49 | |||
| 50 | # plain-Perl code from MIME::Base64 | ||
| 51 | *encode = \&encode_base64; | ||
| 52 | *decode = \&decode_base64; | ||
| 53 | |||
| 54 | sub encode_base64url { | ||
| 55 | my $e = encode_base64(shift, ""); | ||
| 56 | $e =~ s/=+\z//; | ||
| 57 | $e =~ tr[+/][-_]; | ||
| 58 | return $e; | ||
| 59 | } | ||
| 60 | |||
| 61 | sub decode_base64url { | ||
| 62 | my $s = shift; | ||
| 63 | $s =~ tr[-_][+/]; | ||
| 64 | $s .= '=' while length($s) % 4; | ||
| 65 | return decode_base64($s); | ||
| 66 | } | ||
| 67 | |||
| 68 | 1; | ||
| 69 | |||
| 70 | __END__ |