1 // **********************************************************************
3 // Copyright (c) 2003-2011 ZeroC, Inc. All rights reserved.
5 // This copy of Ice is licensed to you under the terms described in the
6 // ICE_LICENSE file included in this distribution.
8 // **********************************************************************
10 #include <Ice/Base64.h>
16 IceInternal::Base64::encode(const vector
<unsigned char>& plainSeq
)
20 if(plainSeq
.size() == 0)
25 // Reserve enough space for the returned base64 string
26 size_t base64Bytes
= (((plainSeq
.size() * 4) / 3) + 1);
27 size_t newlineBytes
= (((base64Bytes
* 2) / 76) + 1);
28 size_t totalBytes
= base64Bytes
+ newlineBytes
;
30 retval
.reserve(totalBytes
);
32 unsigned char by1
= 0;
33 unsigned char by2
= 0;
34 unsigned char by3
= 0;
35 unsigned char by4
= 0;
36 unsigned char by5
= 0;
37 unsigned char by6
= 0;
38 unsigned char by7
= 0;
40 for(size_t i
= 0; i
< plainSeq
.size(); i
+= 3)
46 if((i
+ 1) < plainSeq
.size())
51 if((i
+ 2) < plainSeq
.size())
57 by5
= ((by1
& 0x3) << 4) | (by2
>> 4);
58 by6
= ((by2
& 0xf) << 2) | (by3
>> 6);
61 retval
+= encode(by4
);
62 retval
+= encode(by5
);
64 if((i
+ 1) < plainSeq
.size())
66 retval
+= encode(by6
);
73 if((i
+ 2) < plainSeq
.size())
75 retval
+= encode(by7
);
84 outString
.reserve(totalBytes
);
85 string::iterator iter
= retval
.begin();
87 while((retval
.end() - iter
) > 76)
89 copy(iter
, iter
+76, back_inserter(outString
));
94 copy(iter
, retval
.end(), back_inserter(outString
));
100 IceInternal::Base64::decode(const string
& str
)
104 newStr
.reserve(str
.length());
106 for(size_t j
= 0; j
< str
.length(); j
++)
114 vector
<unsigned char> retval
;
116 if(newStr
.length() == 0)
121 // Note: This is how we were previously computing the size of the return
122 // sequence. The method below is more efficient (and correct).
123 // size_t lines = str.size() / 78;
124 // size_t totalBytes = (lines * 76) + (((str.size() - (lines * 78)) * 3) / 4);
126 // Figure out how long the final sequence is going to be.
127 size_t totalBytes
= (newStr
.size() * 3 / 4) + 1;
129 retval
.reserve(totalBytes
);
131 unsigned char by1
= 0;
132 unsigned char by2
= 0;
133 unsigned char by3
= 0;
134 unsigned char by4
= 0;
138 for(size_t i
= 0; i
< newStr
.length(); i
+= 4)
147 if((i
+ 1) < newStr
.length())
152 if((i
+ 2) < newStr
.length())
157 if((i
+ 3) < newStr
.length())
167 retval
.push_back((by1
<< 2) | (by2
>> 4));
171 retval
.push_back(((by2
& 0xf) << 4) | (by3
>> 2));
176 retval
.push_back(((by3
& 0x3) << 6) | by4
);
184 IceInternal::Base64::isBase64(char c
)
186 if(c
>= 'A' && c
<= 'Z')
191 if(c
>= 'a' && c
<= 'z')
196 if(c
>= '0' && c
<= '9')
220 IceInternal::Base64::encode(unsigned char uc
)
229 return 'a' + (uc
- 26);
234 return '0' + (uc
- 52);
246 IceInternal::Base64::decode(char c
)
248 if(c
>= 'A' && c
<= 'Z')
253 if(c
>= 'a' && c
<= 'z')
258 if(c
>= '0' && c
<= '9')