In any case, never copy this but use the same SV since
[p5sagit/p5-mst-13.2.git] / ext / MIME / Base64 / Base64.pm
1 #
2 # $Id: Base64.pm,v 2.19 2002/12/28 06:32:37 gisle Exp $
3
4 package MIME::Base64;
5
6 =head1 NAME
7
8 MIME::Base64 - Encoding and decoding of base64 strings
9
10 =head1 SYNOPSIS
11
12  use MIME::Base64;
13
14  $encoded = encode_base64('Aladdin:open sesame');
15  $decoded = decode_base64($encoded);
16
17 =head1 DESCRIPTION
18
19 This module provides functions to encode and decode strings into the
20 Base64 encoding specified in RFC 2045 - I<MIME (Multipurpose Internet
21 Mail Extensions)>. The Base64 encoding is designed to represent
22 arbitrary sequences of octets in a form that need not be humanly
23 readable. A 65-character subset ([A-Za-z0-9+/=]) of US-ASCII is used,
24 enabling 6 bits to be represented per printable character.
25
26 The following functions are provided:
27
28 =over 4
29
30 =item encode_base64($str, [$eol])
31
32 Encode data by calling the encode_base64() function.  The first
33 argument is the string to encode.  The second argument is the line
34 ending sequence to use (it is optional and defaults to C<"\n">).  The
35 returned encoded string is broken into lines of no more than 76
36 characters each and it will end with $eol unless it is empty.  Pass an
37 empty string as second argument if you do not want the encoded string
38 broken into lines.
39
40 =item decode_base64($str)
41
42 Decode a base64 string by calling the decode_base64() function.  This
43 function takes a single argument which is the string to decode and
44 returns the decoded data.
45
46 Any character not part of the 65-character base64 subset set is
47 silently ignored.  Characters occuring after a '=' padding character
48 are never decoded.
49
50 If the length of the string to decode (after ignoring
51 non-base64 chars) is not a multiple of 4 or padding occurs too early,
52 then a warning is generated if perl is running under C<-w>.
53
54 =back
55
56 If you prefer not to import these routines into your namespace you can
57 call them as:
58
59     use MIME::Base64 ();
60     $encoded = MIME::Base64::encode($decoded);
61     $decoded = MIME::Base64::decode($encoded);
62
63 =head1 DIAGNOSTICS
64
65 The following warnings might be generated if perl is invoked with the
66 C<-w> switch:
67
68 =over 4
69
70 =item Premature end of base64 data
71
72 The number of characters to decode is not a multiple of 4.  Legal
73 base64 data should be padded with one or two "=" characters to make
74 its length a multiple of 4.  The decoded result will anyway be as if
75 the padding was there.
76
77 =item Premature padding of base64 data
78
79 The '=' padding character occurs as the first or second character
80 in a base64 quartet.
81
82 =back
83
84 =head1 EXAMPLES
85
86 If you want to encode a large file, you should encode it in chunks
87 that are a multiple of 57 bytes.  This ensures that the base64 lines
88 line up and that you do not end up with padding in the middle. 57
89 bytes of data fills one complete base64 line (76 == 57*4/3):
90
91    use MIME::Base64 qw(encode_base64);
92
93    open(FILE, "/var/log/wtmp") or die "$!";
94    while (read(FILE, $buf, 60*57)) {
95        print encode_base64($buf);
96    }
97
98 or if you know you have enough memory
99
100    use MIME::Base64 qw(encode_base64);
101    local($/) = undef;  # slurp
102    print encode_base64(<STDIN>);
103
104 The same approach as a command line:
105
106    perl -MMIME::Base64 -0777 -ne 'print encode_base64($_)' <file
107
108 Decoding does not need slurp mode if all the lines contains a multiple
109 of 4 base64 chars:
110
111    perl -MMIME::Base64 -ne 'print decode_base64($_)' <file
112
113 =head1 COPYRIGHT
114
115 Copyright 1995-1999, 2001 Gisle Aas.
116
117 This library is free software; you can redistribute it and/or
118 modify it under the same terms as Perl itself.
119
120 Distantly based on LWP::Base64 written by Martijn Koster
121 <m.koster@nexor.co.uk> and Joerg Reichelt <j.reichelt@nexor.co.uk> and
122 code posted to comp.lang.perl <3pd2lp$6gf@wsinti07.win.tue.nl> by Hans
123 Mulder <hansm@wsinti07.win.tue.nl>
124
125 The XS implementation use code from metamail.  Copyright 1991 Bell
126 Communications Research, Inc. (Bellcore)
127
128 =cut
129
130 use strict;
131 use vars qw(@ISA @EXPORT $VERSION $OLD_CODE);
132
133 require Exporter;
134 require DynaLoader;
135 @ISA = qw(Exporter DynaLoader);
136 @EXPORT = qw(encode_base64 decode_base64);
137
138 $VERSION = '2.13';
139
140 eval { bootstrap MIME::Base64 $VERSION; };
141 if ($@) {
142     # can't bootstrap XS implementation, use perl implementation
143     *encode_base64 = \&old_encode_base64;
144     *decode_base64 = \&old_decode_base64;
145
146     $OLD_CODE = $@;
147     #warn $@ if $^W;
148 }
149
150 # Historically this module has been implemented as pure perl code.
151 # The XS implementation runs about 20 times faster, but the Perl
152 # code might be more portable, so it is still here.
153
154 use integer;
155
156 sub old_encode_base64 ($;$)
157 {
158     my $eol = $_[1];
159     $eol = "\n" unless defined $eol;
160
161     my $res = pack("u", $_[0]);
162     # Remove first character of each line, remove newlines
163     $res =~ s/^.//mg;
164     $res =~ s/\n//g;
165
166     $res =~ tr|` -_|AA-Za-z0-9+/|;               # `# help emacs
167     # fix padding at the end
168     my $padding = (3 - length($_[0]) % 3) % 3;
169     $res =~ s/.{$padding}$/'=' x $padding/e if $padding;
170     # break encoded string into lines of no more than 76 characters each
171     if (length $eol) {
172         $res =~ s/(.{1,76})/$1$eol/g;
173     }
174     return $res;
175 }
176
177
178 sub old_decode_base64 ($)
179 {
180     local($^W) = 0; # unpack("u",...) gives bogus warning in 5.00[123]
181
182     my $str = shift;
183     $str =~ tr|A-Za-z0-9+=/||cd;            # remove non-base64 chars
184     if (length($str) % 4) {
185         require Carp;
186         Carp::carp("Length of base64 data not a multiple of 4")
187     }
188     $str =~ s/=+$//;                        # remove padding
189     $str =~ tr|A-Za-z0-9+/| -_|;            # convert to uuencoded format
190
191     ## I guess this could be written as
192     #return unpack("u", join('', map( chr(32 + length($_)*3/4) . $_,
193     #                   $str =~ /(.{1,60})/gs) ) );
194     ## but I do not like that...
195     my $uustr = '';
196     my ($i, $l);
197     $l = length($str) - 60;
198     for ($i = 0; $i <= $l; $i += 60) {
199         $uustr .= "M" . substr($str, $i, 60);
200     }
201     $str = substr($str, $i);
202     # and any leftover chars
203     if ($str ne "") {
204         $uustr .= chr(32 + length($str)*3/4) . $str;
205     }
206     return unpack ("u", $uustr);
207 }
208
209 # Set up aliases so that these functions also can be called as
210 #
211 #    MIME::Base64::encode();
212 #    MIME::Base64::decode();
213
214 *encode = \&encode_base64;
215 *decode = \&decode_base64;
216
217 1;