Bincimap 2.0.16
Easy Imapping
Loading...
Searching...
No Matches
base64.cc
Go to the documentation of this file.
1
7#include "base64.h"
8#include <string>
9#include <iostream>
10
11using namespace ::std;
12
13typedef unsigned char bbyte; /* Byte type */
14
15#define TRUE 1
16#define FALSE 0
17
18#define LINELEN 72 /* Encoded line length (max 76) */
19
20static bbyte dtable[256];
21
22string Binc::base64encode(const string &s_in)
23{
24 int i;
25 string result;
26
27 /* Fill dtable with character encodings. */
28
29 for (i = 0; i < 26; i++) {
30 dtable[i] = 'A' + i;
31 dtable[26 + i] = 'a' + i;
32 }
33 for (i = 0; i < 10; i++) {
34 dtable[52 + i] = '0' + i;
35 }
36 dtable[62] = '+';
37 dtable[63] = '/';
38
39 string::const_iterator s_i = s_in.begin();
40 while (s_i != s_in.end()) {
41
42 bbyte igroup[3], ogroup[4];
43 int c, n;
44
45 igroup[0] = igroup[1] = igroup[2] = 0;
46 for (n = 0; n < 3 && s_i != s_in.end(); n++) {
47 c = *s_i++;
48 igroup[n] = (bbyte) c;
49 }
50 if (n > 0) {
51 ogroup[0] = dtable[igroup[0] >> 2];
52 ogroup[1] = dtable[((igroup[0] & 3) << 4) | (igroup[1] >> 4)];
53 ogroup[2] = dtable[((igroup[1] & 0xF) << 2) | (igroup[2] >> 6)];
54 ogroup[3] = dtable[igroup[2] & 0x3F];
55
56 /* Replace characters in output stream with "=" pad
57 characters if fewer than three characters were
58 read from the end of the input stream. */
59
60 if (n < 3) {
61 ogroup[3] = '=';
62 if (n < 2) {
63 ogroup[2] = '=';
64 }
65 }
66
67 for (i = 0; i < 4; i++)
68 result += ogroup[i];
69 }
70 }
71
72 return result;
73}
74
75string Binc::base64decode(const string &s_in)
76{
77 string result;
78 int i;
79
80 for (i = 0; i < 255; i++) {
81 dtable[i] = 0x80;
82 }
83 for (i = 'A'; i <= 'Z'; i++) {
84 dtable[i] = 0 + (i - 'A');
85 }
86 for (i = 'a'; i <= 'z'; i++) {
87 dtable[i] = 26 + (i - 'a');
88 }
89 for (i = '0'; i <= '9'; i++) {
90 dtable[i] = 52 + (i - '0');
91 }
92 dtable[(int) '+'] = 62;
93 dtable[(int) '/'] = 63;
94 dtable[(int) '='] = 0;
95
96 /*CONSTANTCONDITION*/
97 string::const_iterator s_i = s_in.begin();
98 while (s_i != s_in.end()) {
99 bbyte a[4], b[4], o[3];
100
101 for (i = 0; i < 4 && s_i != s_in.end(); i++) {
102 int c = *s_i++;
103 if (dtable[c] & 0x80) return result;
104 a[i] = (bbyte) c;
105 b[i] = (bbyte) dtable[c];
106 }
107
108 o[0] = (b[0] << 2) | (b[1] >> 4);
109 o[1] = (b[1] << 4) | (b[2] >> 2);
110 o[2] = (b[2] << 6) | b[3];
111
112 i = a[2] == '=' ? 1 : (a[3] == '=' ? 2 : 3);
113
114 for (int j = 0; j < i; ++j)
115 result += o[j];
116
117 if (i < 3) break;
118 }
119
120 return result;
121}
unsigned char bbyte
Definition: base64.cc:13
Declaration of base64 Utilities.
std::string base64decode(const std::string &s_in)
std::string base64encode(const std::string &s_in)