1 /**************************************************************
2 *
3 * Licensed to the Apache Software Foundation (ASF) under one
4 * or more contributor license agreements. See the NOTICE file
5 * distributed with this work for additional information
6 * regarding copyright ownership. The ASF licenses this file
7 * to you under the Apache License, Version 2.0 (the
8 * "License"); you may not use this file except in compliance
9 * with the License. You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing,
14 * software distributed under the License is distributed on an
15 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16 * KIND, either express or implied. See the License for the
17 * specific language governing permissions and limitations
18 * under the License.
19 *
20 *************************************************************/
21
22
23
24 #include <stdio.h>
25 #include <string.h>
26 #include "base64.h"
27
28 static const char base64_tab[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
29
base64_encode(FILE * fin,FILE * fout)30 extern "C" size_t base64_encode( FILE *fin, FILE *fout )
31 {
32 size_t nBytesRead = 0;
33 size_t nLineLength = 0;
34 size_t nBytesWritten = 0;
35
36 size_t nBytes = 0;
37
38 do
39 {
40 unsigned char in_buffer[3];
41
42 memset( in_buffer, 0, sizeof(in_buffer) );
43 nBytes = fread( in_buffer, 1, sizeof(in_buffer), fin );
44 nBytesRead += nBytes;
45
46 if ( nBytes )
47 {
48 unsigned long value =
49 ((unsigned long)in_buffer[0]) << 16 |
50 ((unsigned long)in_buffer[1]) << 8 |
51 ((unsigned long)in_buffer[2]) << 0;
52
53 unsigned char out_buffer[4];
54
55 memset( out_buffer, '=', sizeof(out_buffer) );
56
57 out_buffer[0] = base64_tab[(value >> 18) & 0x3F];
58 out_buffer[1] = base64_tab[(value >> 12) & 0x3F];
59
60 if ( nBytes > 1 )
61 {
62 out_buffer[2] = base64_tab[(value >> 6) & 0x3F];
63 if ( nBytes > 2 )
64 out_buffer[3] = base64_tab[(value >> 0) & 0x3F];
65 }
66
67 if ( nLineLength >= 76 )
68 {
69 fputs( "\n", fout );
70 nLineLength = 0;
71 }
72
73 nBytesWritten += fwrite( out_buffer, 1, sizeof(out_buffer), fout );
74 nLineLength += sizeof(out_buffer);
75 }
76 } while ( nBytes );
77
78 return nBytesWritten;
79 }
80