1 |
# |
2 |
# Library inspired by the Perl 4 code from base64.pl by A. P. Barrett |
3 |
# <barrett@ee.und.ac.za>, October 1993, and subsequent changes by |
4 |
# Earl Hood <earl@earlhood.com> to use MIME::Base64 if available. |
5 |
# |
6 |
|
7 |
package base64; |
8 |
|
9 |
my $use_MIMEBase64 = eval { require MIME::Base64; }; |
10 |
|
11 |
sub b64decode |
12 |
{ |
13 |
return &MIME::Base64::decode_base64(@_) if $use_MIMEBase64; |
14 |
|
15 |
local($^W) = 0; |
16 |
use integer; # should be faster and more accurate |
17 |
|
18 |
( my $str = shift ) =~ tr|A-Za-z0-9+=/||cd; |
19 |
$str =~ s/=+$//; |
20 |
$str =~ tr|A-Za-z0-9+/| -_|; # collapse base64 unto continuous set of chars |
21 |
# (by convention the uuencode set, for unpack) |
22 |
|
23 |
return "" unless $str; |
24 |
return unpack("u", join('', map( chr(32 + length($_)*3/4) . $_, |
25 |
$str =~ /(.{1,60})/gs) ) ); |
26 |
} |
27 |
|
28 |
sub b64encode |
29 |
{ |
30 |
return &MIME::Base64::encode_base64(@_) if $use_MIMEBase64; |
31 |
|
32 |
local ($_) = shift; |
33 |
local($^W) = 0; |
34 |
use integer; # should be faster and more accurate |
35 |
|
36 |
my $result = pack("u", $_[0]); |
37 |
$result =~ s/^.//mg; |
38 |
$result =~ s/\n//g; |
39 |
|
40 |
$result =~ tr| -_|A-Za-z0-9+/|; |
41 |
my $padding = (3 - length($_[0]) % 3) % 3; |
42 |
|
43 |
$result =~ s/.{$padding}$/'=' x $padding/e if $padding; |
44 |
if (length $eol) { |
45 |
$result =~ s/(.{1,76})/$1$eol/g; |
46 |
} |
47 |
return $result; |
48 |
} |
49 |
|
50 |
1; |