2 * \file l4util/lib/src/base64.c
6 * \author Joerg Nothnagel <jn6@os.inf.tu-dresden.de>
9 //code adapted from b64.c
11 /*********************************************************************\
15 AUTHOR: Bob Trower 08/04/01
17 PROJECT: Crypt Data Packaging
19 COPYRIGHT: Copyright (c) Trantor Standard Systems Inc., 2001
21 NOTE: This source code may be used as you wish, subject to
22 the MIT license. See the LICENCE section below.
25 This little utility implements the Base64
26 Content-Transfer-Encoding standard described in
27 RFC1113 (http://www.faqs.org/rfcs/rfc1113.html).
29 This is the coding scheme used by MIME to allow
30 binary data to be transferred by SMTP mail.
32 Groups of 3 bytes from a binary stream are coded as
33 groups of 4 bytes in a text stream.
35 The input stream is 'padded' with zeros to create
36 an input that is an even multiple of 3.
38 A special character ('=') is used to denote padding so
39 that the stream can be decoded back to its exact size.
41 Encoded output is formatted in lines which should
42 be a maximum of 72 characters to conform to the
43 specification. This program defaults to 72 characters,
44 but will allow more or less through the use of a
45 switch. The program enforces a minimum line size
50 The stream 'ABCD' is 32 bits long. It is mapped as
55 A (65) B (66) C (67) D (68) (None) (None)
56 01000001 01000010 01000011 01000100
58 16 (Q) 20 (U) 9 (J) 3 (D) 17 (R) 0 (A) NA (=) NA (=)
59 010000 010100 001001 000011 010001 000000 000000 000000
64 Decoding is the process in reverse. A 'decode' lookup
65 table has been created to avoid string scans.
67 DESIGN GOALS: Specifically:
68 Code is a stand-alone utility to perform base64
69 encoding/decoding. It should be genuinely useful
70 when the need arises and it meets a need that is
71 likely to occur for some users.
72 Code acts as sample code to show the author's
73 design and coding style.
76 This program is designed to survive:
77 Everything you need is in a single source file.
78 It compiles cleanly using a vanilla ANSI C compiler.
79 It does its job correctly with a minimum of fuss.
80 The code is not overly clever, not overly simplistic
81 and not overly verbose.
82 Access is 'cut and paste' from a web page.
83 Terms of use are reasonable.
85 VALIDATION: Non-trivial code is never without errors. This
86 file likely has some problems, since it has only
87 been tested by the author. It is expected with most
88 source code that there is a period of 'burn-in' when
89 problems are identified and corrected. That being
90 said, it is possible to have 'reasonably correct'
91 code by following a regime of unit test that covers
92 the most likely cases and regression testing prior
93 to release. This has been done with this code and
94 it has a good probability of performing as expected.
100 (Zero length target file created
101 on both encode and decode.)
103 case 1:One input character:
104 CASE1.DAT A -> QQ== -> A
106 case 2:Two input characters:
107 CASE2.DAT AB -> QUJD -> AB
109 case 3:Three input characters:
110 CASE3.DAT ABC -> QUJD -> ABC
112 case 4:Four input characters:
113 case4.dat ABCD -> QUJDRA== -> ABCD
115 case 5:All chars from 0 to ff, linesize set to 50:
117 AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIj
118 JCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZH
119 SElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWpr
120 bG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6P
121 kJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKz
122 tLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX
123 2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7
126 case 6:Mime Block from e-mail:
127 (Data same as test case 5)
130 Tested 28 MB file in/out.
132 case 8: Random Binary Integrity:
133 This binary program (b64.exe) was encoded to base64,
134 back to binary and then executed.
137 All files in a working directory encoded/decoded
138 and compared with file comparison utility to
139 ensure that multiple runs do not cause problems
140 such as exhausting file handles, tmp storage, etc.
144 Syntax, operation and failure:
145 All options/switches tested. Performs as
149 No Args -- Shows Usage Screen
150 Return Code 1 (Invalid Syntax)
152 One Arg (invalid) -- Shows Usage Screen
153 Return Code 1 (Invalid Syntax)
155 One Arg Help (-?) -- Shows detailed Usage Screen.
156 Return Code 0 (Success -- help request is valid).
158 One Arg Help (-h) -- Shows detailed Usage Screen.
159 Return Code 0 (Success -- help request is valid).
161 One Arg (valid) -- Uses stdin/stdout (filter)
162 Return Code 0 (Sucess)
164 Two Args (invalid file) -- shows system error.
165 Return Code 2 (File Error)
167 Encode non-existent file -- shows system error.
168 Return Code 2 (File Error)
170 Out of disk space -- shows system error.
171 Return Code 3 (File I/O Error)
175 Compile/Regression test:
176 gcc compiled binary under Cygwin
177 Microsoft Visual Studio under Windows 2000
178 Microsoft Version 6.0 C under Windows 2000
182 LICENCE: Copyright (c) 2001 Bob Trower, Trantor Standard Systems Inc.
184 Permission is hereby granted, free of charge, to any person
185 obtaining a copy of this software and associated
186 documentation files (the "Software"), to deal in the
187 Software without restriction, including without limitation
188 the rights to use, copy, modify, merge, publish, distribute,
189 sublicense, and/or sell copies of the Software, and to
190 permit persons to whom the Software is furnished to do so,
191 subject to the following conditions:
193 The above copyright notice and this permission notice shall
194 be included in all copies or substantial portions of the
197 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
198 KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
199 WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
200 PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
201 OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
202 OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
203 OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
204 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
207 Bob Trower 08/04/01 -- Create Version 0.00.00B
209 \******************************************************************* */
214 #include <l4/util/base64.h> // we implement these functions
223 * \ingroup utils_internal
224 * Translation Table as described in RFC1113
226 static const char cb64[]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
229 * \ingroup utils_internal
230 * Translation Table to decode (created by Bob Trower)
232 static const char cd64[]="|$$$}rstuvwxyz{$$$$$$$>?@ABCDEFGHIJKLMNOPQRSTUVW$$$$$$XYZ[\\]^_`abcdefghijklmnopq";
237 * \brief encode 3 8-bit binary bytes as 4 '6-bit' characters
238 * \ingroup utils_internal
241 * \param in array of bytes to be encoded
242 * \param len real number of bytes to encode
243 * \retval out encoded representation of \a in
244 * encode 3 8-bit binary bytes as 4 '6-bit' characters
246 static void base64_encodeblock(unsigned char in[3], unsigned char out[4], int len);
249 * \brief decode 4 '6-bit' characters into 3 8-bit binary bytes
250 * \ingroup utils_internal
253 * \param in array of bytes to be decoded
254 * \retval out decoded representation of \a in
255 * decode 4 '6-bit' characters into 3 8-bit binary bytes
257 static void base64_decodeblock(unsigned char in[4], unsigned char out[3]);
260 // implementation of public functions
262 void base64_encode( const char *infile, unsigned int in_size, char **outfile)
264 unsigned char in[3], out[4];
266 unsigned int in_count=0, out_count=0;
268 char *temp=malloc(in_size*2);//to be on the safe side;
269 while(in_count<in_size)
272 for( i = 0; i < 3; i++ )
276 in[i] = (unsigned char) infile[in_count++];
286 base64_encodeblock( in, out, len );
287 for( i = 0; i < 4; i++ )
289 temp[out_count++]=out[i];
293 temp[out_count]=0; //null-terminate string
297 void base64_decode( const char*infile, unsigned int in_size, char **outfile )
299 unsigned char in[4], out[3], v;
301 unsigned int in_count=0, out_count=0;
302 char *temp =malloc(in_size); //to be on the safe side;
303 while( in_count<in_size)
305 for( len = 0, i = 0; i < 4 && in_count<in_size; i++ )
308 while( in_count<in_size && v == 0 )
310 v = (unsigned char) infile[in_count++];
311 v = (unsigned char) ((v < 43 || v > 122) ? 0 : cd64[ v - 43 ]);
314 v = (unsigned char) ((v == '$') ? 0 : v - 61);
317 if( in_count<in_size)
322 in[ i ] = (unsigned char) (v - 1);
332 base64_decodeblock( in, out );
333 for( i = 0; i < len - 1; i++ )
335 temp[out_count++]=out[i];
344 // implementation of private functions
346 void base64_encodeblock( unsigned char in[3], unsigned char out[4], int len )
348 out[0] = cb64[ in[0] >> 2 ];
349 out[1] = cb64[ ((in[0] & 0x03) << 4) | ((in[1] & 0xf0) >> 4) ];
350 out[2] = (unsigned char) (len > 1 ? cb64[ ((in[1] & 0x0f) << 2) | ((in[2] & 0xc0) >> 6) ] : '=');
351 out[3] = (unsigned char) (len > 2 ? cb64[ in[2] & 0x3f ] : '=');
354 static void base64_decodeblock( unsigned char in[4], unsigned char out[3] )
356 out[ 0 ] = (unsigned char ) (in[0] << 2 | in[1] >> 4);
357 out[ 1 ] = (unsigned char ) (in[1] << 4 | in[2] >> 2);
358 out[ 2 ] = (unsigned char ) (((in[2] << 6) & 0xc0) | in[3]);