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; # unpack("u",...) gives bogus warning in 5.00[123] |
16 |
use integer; |
17 |
|
18 |
my $str = shift; |
19 |
$str =~ tr|A-Za-z0-9+=/||cd; # remove non-base64 chars |
20 |
if (length($str) % 4) { |
21 |
require Carp; |
22 |
Carp::carp("Length of base64 data not a multiple of 4") |
23 |
} |
24 |
$str =~ s/=+$//; # remove padding |
25 |
$str =~ tr|A-Za-z0-9+/| -_|; # convert to uuencoded format |
26 |
return "" unless length $str; |
27 |
|
28 |
unpack("u", join('', map( chr(32 + length($_)*3/4) . $_, |
29 |
$str =~ /(.{1,60})/gs) ) ); |
30 |
} |
31 |
|
32 |
sub b64encode |
33 |
{ |
34 |
return &MIME::Base64::encode_base64 if $use_MIMEBase64; |
35 |
|
36 |
local ($_) = shift; |
37 |
local($^W) = 0; |
38 |
use integer; # should be faster and more accurate |
39 |
|
40 |
my $result = pack("u", $_); |
41 |
$result =~ s/^.//mg; |
42 |
$result =~ s/\n//g; |
43 |
|
44 |
$result =~ tr|\` -_|AA-Za-z0-9+/|; |
45 |
my $padding = (3 - length($_) % 3) % 3; |
46 |
|
47 |
$result =~ s/.{$padding}$/'=' x $padding/e if $padding; |
48 |
$result =~ s/(.{1,76})/$1\n/g; |
49 |
$result; |
50 |
} |
51 |
|
52 |
1; |